Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
PHP password_hash() cost calculator
* Password Hash Cost Calculator
* Set the ideal time that you want a password_hash() call to take and this
* script will keep testing until it finds the ideal cost value and let you
* know what to set it to when it has finished
// Milliseconds that a hash should take (ideally)
$mSec = 100;
$password = 'MyT3ST_P4$$w0rD';
echo "\nPassword Hash Cost Calculator\n\n";
echo "Testing BCRYPT hashing the password '$password'\n\n";
echo "We're going to run until the time to generate the hash takes longer than {$mSec}ms\n";
$cost = 3;
do {
echo "\nTesting cost value of $cost: ";
$time = benchmark($password, $cost);
echo "... took $time";
} while ($time < ($mSec/1000));
echo "\n\nIdeal cost is $cost\n";
echo "\nRunning 100 times to check the average:\n";
$start = microtime(true);
$times = [];
for ($i=1;$i<=100;$i++) {
echo "\r$i/100";
$times[] = benchmark($password, $cost);
echo "\n\ndone benchmarking in ".(microtime(true)-$start)."\n";
echo "\nSlowest time: ".max($times);
echo "\nFastest time: ".min($times);
echo "\nAverage time: ".(array_sum($times)/count($times));
echo "\n\nFinished\n";
function benchmark($password, $cost=4)
$start = microtime(true);
password_hash($password, PASSWORD_BCRYPT, ['cost'=>$cost]);
return microtime(true) - $start;
Copy link

Antnee commented Feb 29, 2016

Example result:

$ php password_hash_cost_calculator.php

Password Hash Cost Calculator

Testing BCRYPT hashing the password 'MyT3ST_P4$$w0rD'

We're going to run until the time to generate the hash takes longer than 100ms

Testing cost value of 4: ... took 0.0028109550476074
Testing cost value of 5: ... took 0.0027267932891846
Testing cost value of 6: ... took 0.0048871040344238
Testing cost value of 7: ... took 0.010008096694946
Testing cost value of 8: ... took 0.020781993865967
Testing cost value of 9: ... took 0.038994789123535
Testing cost value of 10: ... took 0.077332019805908
Testing cost value of 11: ... took 0.15506601333618

Ideal cost is 11

Running 100 times to check the average:

done benchmarking in 15.389363050461

Slowest time: 0.18689680099487
Fastest time: 0.15069508552551
Average time: 0.15379852294922


Copy link

Dang, great simple tool! This was so helpful

Copy link

Thanks really helpful !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment