benchie.php

#!/usr/bin/php
<?php
/**
 * # Option 1, auto-looping: 
 *
 * 1. create a new dir in this directory
 * 2. Write an init.php & initialize variables that will be used by your bench scripts
 * 3. also set `$bench_loops = 100;` (or whatever # of loops) in the init file.
 * 4. create a new file for each block of code you wish to benchmark & write the code.
 *
 * # Option 2, self-looping (less overhead)
 * 1. create a new dir in this directory
 * 2. Write an init.php file and set `$max_iters = 1000; $i = 0;`
 * 3. create a new file for each block of code you wish to benchmark. 
 * 4. In each bench file write 'while (++$i < $max_iters){` & put your code inside the while loop
 *
 * @arg 1 folder - the directory (inside the php dir) to bench or blank to run all directories
 * @usage ./benchie.php Comparison 
 */

// require_once(__DIR__.'/vendor/autoload.php');

echo "benchies!";

echo "\n\n";


$folder = $argv[1] ?? false;

$dir = __DIR__.'/php';
$dirList = ($folder!==false&&is_dir($dir.'/'.$folder)) ? [$folder] : scandir($dir);

foreach ($dirList as $BenchDir){
    if ($BenchDir=='.'||$BenchDir=='..')continue;
    $name = basename($BenchDir);
    echo "\nBench for $name:";
    $compare = [];
    foreach (scandir($dir.'/'.$BenchDir) as $benchFile){
        if (substr($benchFile,-4)!='.php')continue;
        if (substr($benchFile,-8)=='init.php')continue;

        ob_start();
        if (file_exists($initFile = $dir.'/'.$BenchDir.'/init.php')){
            $bench_loop_index = 0;
            $bench_loops = 1;
            include($initFile);
            $bench_start = microtime(true);
            while($bench_loop_index++<$bench_loops){
                include($dir.'/'.$BenchDir.'/'.$benchFile);
            }
            $bench_end = microtime(true);
        } else {
            $bench_start = microtime(true);
            include($dir.'/'.$BenchDir.'/'.$benchFile);
            $bench_end = microtime(true);
        }
        ob_end_clean();

        $duration = $bench_end - $bench_start;
        $file = pathinfo(basename($benchFile), PATHINFO_FILENAME);
        $compare[$file] = $duration;
    }

    asort($compare, SORT_NUMERIC);

    $firstDuration = array_values($compare)[0];
    foreach ($compare as $name=>$duration){
        echo "\n   $name";
        // echo "\n     Start: $start";
        // echo "\n     End: $end";
        $diff = $duration - $firstDuration;
        echo "\n     Duration: $duration. $diff slower";
    }
}








echo "\n\n";