Skip to content

Instantly share code, notes, and snippets.

@bdelespierre
Last active August 29, 2015 14:00
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 bdelespierre/11036253 to your computer and use it in GitHub Desktop.
Save bdelespierre/11036253 to your computer and use it in GitHub Desktop.
<?php
function formatGUID($chars, $uppercase = false, $braces = false, $hyphen = true)
{
$c = $chars;
$h = $hyphen ? '-' : '';
$g =
"{$c[00]}{$c[01]}{$c[02]}{$c[03]}{$c[04]}{$c[05]}{$c[06]}{$c[07]}{$h}".
"{$c[08]}{$c[09]}{$c[10]}{$c[11]}{$h}".
"{$c[12]}{$c[13]}{$c[14]}{$c[15]}{$h}".
"{$c[16]}{$c[17]}{$c[18]}{$c[19]}{$h}".
"{$c[20]}{$c[21]}{$c[22]}{$c[23]}{$c[24]}{$c[25]}{$c[26]}{$c[27]}{$c[28]}{$c[29]}{$c[30]}{$c[31]}";
$uppercase && $g = strtoupper($g);
$braces && $g = "\{$g\}";
return $g;
}
function rand_1() { return md5(uniqid(rand(), true)); }
function rand_2() { return bin2hex(openssl_random_pseudo_bytes(16, $strong)); }
function rand_3()
{
static $handle;
if (!isset($handle)) {
$handle = fopen('/dev/urandom', 'rb');
if ($handle === false)
return false;
}
return bin2hex(fread($handle, 16));
}
$iterations = isset($argv[1]) ? (int)$argv[1] : 10000;
$repeat = isset($argv[2]) ? (int)$argv[2] : 1;
$loop = 0;
$memorycap = return_bytes(ini_get('memory_limit')) - 104857600; // max - 1MB
while (($repeat == -1 ? true : $repeat--) && ++$loop) {
for ($num=1; $num<=3; $num++) {
$func = "rand_{$num}";
$st = microtime(true);
for ($i=0; $i<$iterations; $i++) {
$guid = formatGUID($func());
if (isset($guids[$num][$guid]))
trigger_error("Alogrithm #$num created a collision !", E_USER_NOTICE);
else
$guids[$num][$guid] = true;
}
$nd = microtime(true);
$me = memory_get_usage();
echo str_pad(get_bytes($me), 10, ' ', STR_PAD_LEFT) . " [$loop:$num] ", round(($nd - $st) * 1000000), "µs \r";
}
if ($me >= $memorycap)
unset($guids);
}
function return_bytes($val)
{
$val = trim($val);
$last = strtolower($val[strlen($val)-1]);
switch($last) {
// The 'G' modifier is available since PHP 5.1.0
case 'g':
$val *= 1024;
case 'm':
$val *= 1024;
case 'k':
$val *= 1024;
}
return $val;
}
function get_bytes($val)
{
if ($val > 1000) {
$val /= 1024;
$unit = 'k';
}
if ($val > 1000) {
$val /= 1024;
$unit = 'm';
}
if ($val > 1000) {
$val /= 1024;
$unit = 'g';
}
return round($val,2).strtoupper($unit)."B";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment