Created
December 13, 2011 22:47
-
-
Save avargas/1474305 to your computer and use it in GitHub Desktop.
proof of concept quick and simple php benchmarking and profiling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function ticks_counter ($return = null) | |
{ | |
static $ticks; | |
if ($return) { | |
return $ticks; | |
} | |
$ticks++; | |
} | |
declare (ticks = 1); | |
register_tick_function('ticks_counter'); | |
# pmu: Peak Memory Usage | |
# mu: Memory Usage | |
# cpu: CPU Time | |
# wt: Wall Time | |
# ct: | |
# exclusive wall times, memory usage, CPU times and number of calls for each function. | |
$BENCHMARKS = array(); | |
$RUNNING = false; | |
function bench ($name) | |
{ | |
global $BENCHMARKS, $RUNNING; | |
if ($RUNNING) { | |
throw new Exception('A benchmark is already running'); | |
} | |
xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY); | |
$id = count($BENCHMARKS); | |
$BENCHMARKS[$id] = array( | |
'name'=>$name, | |
'id'=>$id, | |
'files'=>get_included_files(), | |
'ticks'=>ticks_counter(true) | |
); | |
$running = $id; | |
return $id; | |
} | |
function endbench ($id) | |
{ | |
global $BENCHMARKS; | |
if (!isset($BENCHMARKS[$id])) { | |
throw new Exception('benchmark #' . $id . ' not found in stack'); | |
} | |
$bench = $BENCHMARKS[$id]; | |
$ticks = ticks_counter(true); | |
$xhprof = xhprof_disable(); | |
$RUNNING = false; | |
$xhprof = end($xhprof); | |
$included = array_diff(get_included_files(), $bench['files']); | |
foreach (array('wt', 'cpu') as $k) { | |
$xhprof[$k . '_milli'] = $xhprof[$k] > 0 ? $xhprof[$k] / 1000 : 0; | |
$xhprof[$k . '_sec'] = $xhprof[$k] > 0 ? $xhprof[$k] / 1000000 : 0; | |
} | |
foreach (array('mu', 'pmu') as $k) { | |
$xhprof[$k . '_kb'] = $xhprof[$k] > 0 ? $xhprof[$k] / 1024 : 0; | |
$xhprof[$k . '_mb'] = $xhprof[$k] > 0 ? $xhprof[$k] / 1024 / 1024 : 0; | |
} | |
return array( | |
'ticks'=>$ticks - $bench['ticks'], | |
'included_files'=>$included, | |
'xhprof'=>$xhprof | |
); | |
} | |
$id = bench('test'); | |
# ... code | |
var_dump(endbench($id)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment