greglamb
4/28/2014 - 3:00 PM

Handy Benchmarking Function

Handy Benchmarking Function

<?php

namespace Foo\Bar {
    class Baz {}
}

namespace {
    
    include 'benchmark.php';
    
    $iters = 100000;
    $testCls = new Foo\Bar\Baz();
    
    benchmark('Reflection-Based', $iters, function () use ($testCls) {
        $name = (new ReflectionClass($testCls))->getShortName();
    });
    
    benchmark('get_class-Based', $iters, function () use ($testCls) {
        $nsParts = explode('\\', get_class($testCls));
        $name = reset($nsParts);
    });
}
<?php

function benchmark($name, $iterations, Closure $function)
{
    echo "Starting Benchmark: {$name} (".number_format($iterations)." Iterations)\n";
    $start = microtime(true);
    for ($i = 0; $i < $iterations; $i++) {
        $function();
    }
    $elapsed = microtime(true) - $start;
    $elapsedMean = number_format(($elapsed / $iterations) * 1000, 4);
    $elapsedTotal = number_format($elapsed, 4);
    echo "    Total Time: {$elapsedTotal}s\n";
    echo "    Mean Time:  {$elapsedMean}ms\n\n";
}