A timer class

Written by Ben Wendt

It’s often useful to time aspects of your applications. In environments without access to profiling tools like xdebug, it is necessary to roll your own. Here’s one that relies heavily on calls to microtime. Unfortunately making many thousands of calls to microtime takes a significant amount of time on its own.

But a manual timing class like this can still be quite useful in identifying problem blocks of code:

class Timer {

    private $starts = array();
    private $calls = array();

    private $times = array();

    public function start($identifier) {
        if (!isset($this->calls[$identifier])) {
            $this->calls[$identifier] = 0;
        $this->starts[$identifier] = microtime(true);

    public function stop($identifier) {
        $end = microtime(true);
        if (!isset($this->times[$identifier])) {
            $this->times[$identifier] = 0;
        $this->times[$identifier] += ($end - $this->starts[$identifier]);

    public function getTimes() {
        return $this->times;

    public function getCallCounts() {
        return $this->calls;