Skip to content

Instantly share code, notes, and snippets.

@shello
Created February 8, 2016 14:11
Show Gist options
  • Save shello/9a4a04055ad618ccba14 to your computer and use it in GitHub Desktop.
Save shello/9a4a04055ad618ccba14 to your computer and use it in GitHub Desktop.
<?php
/**
* `password_hash`/bcrypt cost benchmark script
*
* Usage:
* $ php bcrypt_cost_benchmark.php <lower cost> <higher cost> <n_tries>
*
* Example: Run 100 tries of costs 8 through 12
* $ php bcrypt_cost_benchmark.php 8 12 100
*/
if ($argc < 4) {
echo "Usage: {$argv[0]} <lower cost> <higher cost> <n_tries>\n";
exit(1);
}
$cost_lower = intval($argv[1]);
$cost_upper = intval($argv[2]);
$string = 'DjpK|WsAqqk",/@ANXIDDbiU%R';
$tries = intval($argv[3]);
// Run the benchmark
$rawdata = [];
for ($cost = $cost_lower; $cost <= $cost_upper; $cost += 1) {
$rawdata[$cost] = [];
$cost_progress = sprintf("Benchmarking cost: %2d", $cost);
printf($cost_progress); flush();
for ($n = 0; $n < $tries; $n += 1) {
$time_start = microtime(true);
password_hash($string, PASSWORD_BCRYPT, ['cost' => $cost]);
$time_end = microtime(true);
$delta = $time_end - $time_start;
$rawdata[$cost][] = $delta;
}
echo(str_repeat("\x08", strlen($cost_progress))); flush();
}
// Calculate mean and std-dev
$results = [];
for ($cost = $cost_lower; $cost <= $cost_upper; $cost += 1) {
$results[$cost] = [];
$sum = array_sum($rawdata[$cost]);
$mean = $sum / $tries;
$results[$cost]['mean'] = $mean;
// Variance
$sq_diff = array_map(
function ($n) use ($mean) { return ($n - $mean) ** 2; },
$rawdata[$cost]
);
$variance = array_sum($sq_diff) / $tries;
$stddev = sqrt($variance);
$results[$cost]['stddev'] = $stddev;
}
// Print the results
$fmt = "%2d: %6.4F ± %6.4F s (%4.1F hashes/s)\n"; // for sprintf
for ($cost = $cost_lower; $cost <= $cost_upper; $cost += 1) {
$result = $results[$cost];
printf(
$fmt, $cost,
round($result['mean'], 4),
round($result['stddev'], 4),
round(1/$result['mean'], 1)
);
}
exit(0);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment