A Simple PHP Benchmarking function

February 1, 2024 note-to-self

I recently needed to find where some performance issues were and didn't have the time to download and figure out any real-life tools, but this basic system helped. I could just sprinkle lg() in the code and it would log the file, line and any information I passed in. It also automatically logs the difference between the last lg() call and the current one.

It's rudimentary but helps in a pinch. For a Laravel project, I just added it at the end of the controller, outside the class, and then it was available for that route. I removed it when I was done.

function lg($context=[])
    static $last;
    static $log;

    if ($log === null) {
        $name= (new \DateTime)->format('Y-m-d_H-i-s');
        $log = "/var/www/html/{$name}.tsv"; # this is the path inside my docker container but is just the docroot

    $etrace = ob_get_clean();
    $trace = explode(PHP_EOL, $etrace);

    $ms   = microtime(true);
    $date = (new \DateTime)->format('Y-m-d H:i:s.u');
    list($m,) = explode(': ', $trace[0]);

    if (is_array($context) || is_object($context)) {
        $context = json_encode((object)$context);

    $time = $ms - $last;

    error_log("{$m}\t{$time}\t{$context}\t{$ms}\t$date\n", 3, $log);
    $last = $ms;