Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
include dirname(__DIR__) . "/vendor/autoload.php";
use Amp\Process\Process;
use function Amp\Promise\all;
const COUNT = 8;
$passwords = [];
for ($i = 0; $i < COUNT; $i++) {
$passwords[] = \random_bytes(20);
}
$start = microtime(true);
foreach ($passwords as $password) {
\password_hash($password, PASSWORD_DEFAULT);
}
$syncTime = microtime(true) - $start;
function get_hash(string $password): \Generator
{
/** @var Process $process */
$process = yield Process::start("php hash.php");
$stdIn = $process->getStdin();
$stdIn->write($password);
$stdIn->close();
$result = '';
$stream = $process->getStdout();
while ($chunk = yield $stream->read()) {
$result .= $chunk;
}
yield $process->join();
return $result;
}
$asyncTime = 0;
Amp\Loop::run(function() use($passwords, &$asyncTime) {
$promises = [];
foreach ($passwords as $i => $password) {
$promises[] = new \Amp\Coroutine(get_hash($password));
}
$start = microtime(true);
yield all($promises);
$asyncTime = microtime(true) - $start;
});
?>
Hashing <?= COUNT ?> passwords synchronously took <?= $syncTime ?> seconds
Hashing <?= COUNT ?> passwords asynchronously took <?= $asyncTime ?> seconds
Async took <?= ($asyncTime / $syncTime) * 100 ?>% of the time that sync took
<?php echo \password_hash(\stream_get_contents(STDIN), PASSWORD_DEFAULT);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment