Skip to content

Instantly share code, notes, and snippets.

@FirePanther
Created January 11, 2017 14:15
Show Gist options
  • Save FirePanther/4c35d9d05064811859e5f24aa17b52a0 to your computer and use it in GitHub Desktop.
Save FirePanther/4c35d9d05064811859e5f24aa17b52a0 to your computer and use it in GitHub Desktop.
Quickly compare the speed of multiple functions
<?php
/**
* Example output:
* function: file_exists(__FILE__);
* time: 1.39806 seconds
* speed: 39.248 %
*
* function: is_file(__FILE__);
* time: 0.3417 seconds
* speed: 85.152 %
*
* function: is_dir(__FILE__) || is_file(__FILE__);
* time: 0.56151 seconds
* speed: 75.6 %
*/
$total = 0;
$content = '';
$executions = 1000000;
test(function(){ file_exists(__FILE__); });
test(function(){ is_file(__FILE__); });
test(function(){ is_dir(__FILE__) || is_file(__FILE__); });
$content = preg_replace_callback('~\{speed:([\d.]+)\}~', function($m) {
global $total;
return round(100 - $m[1] / $total * 100, 3).' %';
}, $content);
echo $content;
function test($func) {
global $total, $content, $executions;
$f = new ReflectionFunction($func);
$body = trim(
implode('',
preg_replace('~^.*?function\s*\([^\)]*\)\s*\{\s*(.*)\s*\}\s*\)?\s*\;?~is', '$1',
array_slice(file($f->getFileName()), $f->getStartLine() - 1, $f->getEndLine() - $f->getStartLine() + 1)
)
)
);
$start = microtime(1);
for ($i = 0; $i <= $executions; $i++) $func();
$time = microtime(1) - $start;
$total += $time;
$content .= 'function: '.$body.PHP_EOL;
$content .= 'time: '.round($time, 5).' seconds'.PHP_EOL;
$content .= 'speed: {speed:'.$time.'}'.PHP_EOL.PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment