Skip to content

Instantly share code, notes, and snippets.

@guedressel
Last active October 1, 2015 08:22
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save guedressel/0789bea4ebc9083e1d0e to your computer and use it in GitHub Desktop.
Simple speed benchmarking utilitiy to test PHP functions for their runtime.
<?php
class Timer {
private $start = 0;
private $stop = 0;
function Timer( $start = TRUE ) {
if ( $start )
$this->start();
}
function start() {
$this->start = microtime(TRUE);
}
function stop() {
$this->stop = microtime(TRUE);
}
function elapsed() {
if ( ! $this->start )
throw new Exception("Timer not started");
if ( ! $this->stop )
return microtime(TRUE) - $this->start;
else
return $this->stop - $this->start;
}
function reset() {
$this->start = 0;
$this->stop = 0;
}
}
class Benchmark {
static function run( $f, $iterations ) {
$args = func_get_args();
array_shift($args);
array_shift($args);
// Note: this way of running benchmark tests
// adds quite a overhead since "call_user_func_array"
// is not the fastest way to execute some code.
// Anyways it shouldn't affect comparison results as long
// all parts of the comparison will be run by this method.
// The delely will be equally applied to all tests.
// TODO: If somebody could show a way to reduce the
// expenses of "call_user_func_array" I will happily apply
// that here.
$timer = new Timer();
for ($i=0; $i<$iterations; $i++) {
call_user_func_array($f, $args);
}
return $timer->elapsed();
}
static function getReport( $duration, $iterations ) {
$r = number_format($duration, 4) . " seconds for $iterations runs.\n";
$r .= number_format(($duration / $iterations), 4) . " seconds per run\n";
return $r;
}
}
$iterations = 100000;
$test_data = array(
"a" => array(
1 => 234.1023,
"two" => "hello world",
),
"b" => array(
"not true" => FALSE,
"not false" => TRUE,
),
);
$test_func = function($data) {
serialize($data);
};
$duration = Benchmark::run( $test_func, $iterations, $test_data );
print Benchmark::getReport($duration, $iterations);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment