PHP: Simple timer for benchmarking methods and code chunks

Published:

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 😎