Skip to content

Instantly share code, notes, and snippets.

@i110
Last active August 29, 2015 14:04
Show Gist options
  • Save i110/169a0baa8cb46acf7220 to your computer and use it in GitHub Desktop.
Save i110/169a0baa8cb46acf7220 to your computer and use it in GitHub Desktop.
decbin benchmarks
<?php
function h_tom($decimal){
$result = array();
$digit = floor(log($decimal,2))+1;
for($i = 0 ; $i < $digit ; $i++)
$result[$i] = $decimal&(1<<$i) ? 1:0;
return $result;
}
function php_decbin($decimal) {
$result = array();
while ($decimal) {
array_push($result, $decimal % 2);
$decimal = floor($decimal / 2);
}
return $result;
}
function i110($decimal) {
$result = array();
while ($decimal) {
array_push($result, $decimal & 1);
$decimal >>= 1;
}
return $result;
}
function bench($names, $count) {
$results = array();
while ($count--) {
foreach ($names as $name) {
$st = microtime(true);;
$name(rand(1, 65535));
$et = microtime(true);;
$results[$name] += $et - $st;
}
}
foreach ($results as $name => $cum) {
echo $name . "\t" . $cum . "\n";
}
}
bench(
array('h_tom', 'i110', 'php_decbin', 'decbin'),
1000000
);
// h_tom 8.1964886188507
// i110 8.3208520412445
// php_decbin 12.559322118759
// decbin 1.5397775173187
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment