PHP: Simple timer for benchmarking methods and code chunks

Wanted a super simple class for seeing how long various parts of my code took. Did some googling and couldn’t really find anything I liked. So I decided that I might as well write my own just for the fun of it. Which I have now done!

Was a bit of a hassle to get it right though, but I think I have managed to get it the way I want now. The trick was I wanted to start new timers inside others to create sort of a tree of timers. This way I can get a view of both how long a full request took, but also how long various sub sections of it ran for.

I have published the code at GitHub so you can download and check out the source there. Since I’ve started to use Composer I also created a package for it and added it to Packagist.

Simple example usage:

<?php

include "Timer.php"; // Unecessary when using Composer auto-loading

function wait_seconds($x)
{
    Timer::start(__METHOD__, func_get_args());
    // Slow work
    sleep($x);
    Timer::stop();
}


Timer::start("timer_example.php");
sleep(1);
wait_seconds(3);

header('content-type: text/plain; charset=utf-8');
echo Timer::result();

Which would output the following:

timer_example.php()
 â”‚
 â”‚ 4.001 s
 â”‚ 1.87 KiB, 746.60 KiB
 â”‚
 â”œ wait_seconds(3)
 â”‚  â”‚
 â”‚  â”‚ 3.000 s
 â”‚  â”‚ 384.00 B, 746.60 KiB
 â”‚ ─┘

Very simple 😎

You can see some more extensive use of this class on a small website I’m playing around with currently at myhymnal.net. On every page there is a tiny Debug link in the bottom right corner which you can click to see the output of the Timer class for that request. You find the source of the website at github.com/svish/MyHymnal.