Showing posts with label uuidv4. Show all posts
Showing posts with label uuidv4. Show all posts

Thursday, September 08, 2016

Whats is the best way to generate uuidv4 in php?

Whats is the best way to generate uuidv4 in php?
Some people use this: https://github.com/ramsey/uuid
Others can user a system call like file_get_contents('/proc/sys/kernel/random/uuid');
And others just a simple function.

What's the best way? Depending on your needs, of course.
I can use all the option, so I decide to make a benchmark, and I was surprised...
/var/www/kits/html/test.php.html
<?php
require __DIR__.'/../vendor/autoload.php';
function gen_uuidv4(){
    return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
            // 32 bits for "time_low"
            mt_rand(0,0xffff),mt_rand(0,0xffff),
            // 16 bits for "time_mid"
            mt_rand(0,0xffff),
            // 16 bits for "time_hi_and_version",
            // four most significant bits holds version number 4
            mt_rand(0,0x0fff)|0x4000,
            // 16 bits, 8 bits for "clk_seq_hi_res",
            // 8 bits for "clk_seq_low",
            // two most significant bits holds zero and one for variant DCE1.1
            mt_rand(0,0x3fff)|0x8000,
            // 48 bits for "node"
            mt_rand(0,0xffff),mt_rand(0,0xffff),mt_rand(0,0xffff));
}
// #####################################
$i=microtime(true);
for($a=0;$a<1000000;$a++){
    file_get_contents('/proc/sys/kernel/random/uuid');
}
$f=microtime(true);
$t1=$f-$i;
echo $t1;
echo '<br>';
// #####################################
$i=microtime(true);
for($a=0;$a<1000000;$a++){
    gen_uuidv4(true);
}
$f=microtime(true);
$t2=$f-$i;
echo $t2;
echo '<br>';
// #####################################
$i=microtime(true);
for($a=0;$a<1000000;$a++){
    \Ramsey\Uuid\Uuid::uuid4();
}
$f=microtime(true);
$t3=$f-$i;
echo $t3;


T1: 10.762820005417(s) System Call in Ubuntu 14.04
T2: 6.3450520038605(s) simple function
T3: 30.962769985199(s) blotted library

Choose wisely :)

systemd-timesyncd

sudo apt update && sudo apt install systemd-timesyncd && sudo systemctl enable --now systemd-timesyncd