Advertisement
Guest User

Untitled

a guest
Feb 8th, 2016
47
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.85 KB | None | 0 0
  1. <?php
  2.  
  3. /**
  4. * `password_hash`/bcrypt cost benchmark script
  5. *
  6. * Usage:
  7. * $ php bcrypt_cost_benchmark.php <lower cost> <higher cost> <n_tries>
  8. *
  9. * Example: Run 100 tries of costs 8 through 12
  10. * $ php bcrypt_cost_benchmark.php 8 12 100
  11. */
  12.  
  13. if ($argc < 4) {
  14. echo "Usage: {$argv[0]} <lower cost> <higher cost> <n_tries>\n";
  15. exit(1);
  16. }
  17.  
  18. $cost_lower = intval($argv[1]);
  19. $cost_upper = intval($argv[2]);
  20. $string = 'DjpK|WsAqqk",/@ANXIDDbiU%R';
  21.  
  22. $tries = intval($argv[3]);
  23.  
  24.  
  25. // Run the benchmark
  26. $rawdata = [];
  27. for ($cost = $cost_lower; $cost <= $cost_upper; $cost += 1) {
  28. $rawdata[$cost] = [];
  29.  
  30. $cost_progress = sprintf("Benchmarking cost: %2d", $cost);
  31. printf($cost_progress); flush();
  32.  
  33. for ($n = 0; $n < $tries; $n += 1) {
  34. $time_start = microtime(true);
  35. password_hash($string, PASSWORD_BCRYPT, ['cost' => $cost]);
  36. $time_end = microtime(true);
  37.  
  38. $delta = $time_end - $time_start;
  39. $rawdata[$cost][] = $delta;
  40. }
  41.  
  42. echo(str_repeat("\x08", strlen($cost_progress))); flush();
  43. }
  44.  
  45.  
  46. // Calculate mean and std-dev
  47. $results = [];
  48. for ($cost = $cost_lower; $cost <= $cost_upper; $cost += 1) {
  49. $results[$cost] = [];
  50.  
  51. $sum = array_sum($rawdata[$cost]);
  52.  
  53. $mean = $sum / $tries;
  54. $results[$cost]['mean'] = $mean;
  55.  
  56. // Variance
  57. $sq_diff = array_map(
  58. function ($n) use ($mean) { return ($n - $mean) ** 2; },
  59. $rawdata[$cost]
  60. );
  61.  
  62. $variance = array_sum($sq_diff) / $tries;
  63. $stddev = sqrt($variance);
  64. $results[$cost]['stddev'] = $stddev;
  65. }
  66.  
  67.  
  68. // Print the results
  69. $fmt = "%2d: %6.4F ± %6.4F s (%4.1F hashes/s)\n"; // for sprintf
  70. for ($cost = $cost_lower; $cost <= $cost_upper; $cost += 1) {
  71. $result = $results[$cost];
  72. printf(
  73. $fmt, $cost,
  74. round($result['mean'], 4),
  75. round($result['stddev'], 4),
  76. round(1/$result['mean'], 1)
  77. );
  78. }
  79.  
  80. exit(0);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement