Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save carcinocron/e09ef8b98aa809880c07 to your computer and use it in GitHub Desktop.
Save carcinocron/e09ef8b98aa809880c07 to your computer and use it in GitHub Desktop.
<pre><?php
/**
The goal is fast + unique, this is not for cryptographically secure purposes!
*/
define('LOOP_COUNT',100000);
define()
$startTime = microtime(true);
for($x=0;$x<LOOP_COUNT;$x++)
{
// Your content to test
$var =mt_rand(100000000000000,999999999999999);
}
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo 'mt_rand in: ',$elapsed,"\n";
$startTime = microtime(true);
for($x=0;$x<LOOP_COUNT;$x++)
{
// Your content to test
$var = openssl_random_pseudo_bytes(14);
}
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo 'openssl_random_pseudo_bytes(14): in ',$elapsed,"\n";
$startTime = microtime(true);
for($x=0;$x< LOOP_COUNT;$x++)
{
// Your content to test
$var = uniqid('',true);
}
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo 'uniqid(\'\',true) in: ',$elapsed,"\n";
$startTime = microtime(true);
for($x=0;$x< LOOP_COUNT;$x++)
{
// Your content to test
$var = uniqid('',false);
}
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo 'uniqid(\'\',false) in: ',$elapsed,"\n";
?>
@carcinocron
Copy link
Author

single threaded assumption results using phpfiddle:

mt_rand in:                         0.0189170837402
openssl_random_pseudo_bytes(14): in 0.0299289226532
uniqid('',true) in:                 0.0488948822021
uniqid('',false) in:                5.48299694061

I expect uniqid('',false) to perform worse in a multi-php-fpm ecosystem. This benchmark shows high performance but does not show high availability (todo!!!)

@carcinocron
Copy link
Author

uniqid calls getdatetime(), but uniqid('',false) does extra blocking to the CPU and uses sleep(1) to guarantee that no other process gets the same value. The extra entropy flag seems to be free or built in, we're just halting and blocking the CPU to ensure that a shorter value is unique, which is a total waist.

@carcinocron
Copy link
Author

my laptop, single threaded:

mt_rand in:                         0.036395788192749
openssl_random_pseudo_bytes(14): in 0.10478019714355
uniqid('',true) in:                 0.050448894500732
uniqid('',false) in:                47.480038881302

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