Lightweight PHP Code Timer

Sep
30

I wanted to profile some of my PHP code to benchmark it and also to help find some bottlenecks. I couldn't find an easy way to do this, so I decided to create my own timer. It is accurate down to microseconds, but milliseconds have been easier for me to work with.

<?php
class Timer {
   private $startTime;

   function __construct() { $this->startTime = microtime(true); }

   function reset() { $this->__construct(); }

   function __toString() {
      return "Elapsed " . (microtime(true) - $this->startTime) * 1000 . " milliseconds.\n";
   }
}

$timer = new Timer();
// code
echo $timer;
$timer->reset();
// more code
echo $timer;
?>

An example output from the code above would be as follows:

Elapsed 0.94294548034668 milliseconds.
Elapsed 3.9780139923096 milliseconds.
comments powered by Disqus