Quantcast
Viewing latest article 6
Browse Latest Browse All 23

PHP: easy to use open-source Timer class

I share my Timer class with you. This is an easy to use class. If you use this you will never have to think about the way of execution time measuring.

PHP Timer class

<?php
/**
* Usage:
* $timer = new Timer();
* // Run some important slow or fast commands...
* echo $timer;
*
* <small>Execution time: 3.456434 sec</small>
*/
class Timer {
    /**
     * Microtime when object has started in second.
     * @var float
     */
    protected $time;

    /**
     * Output string for display ellapsed time.
     * @var string sprintf formatted string.
     */
    protected $template;

    public function __construct($template = '<small>Execution time: %f sec</small>') {
        $this->template = $template;
        $this->reset();
    }

    /**
     * Get elapsed time.
     * @return float Ellapsed time since object creation in second.
     */
    public function getTime() {
        return microtime(TRUE) - $this->time;
    }

    /**
     * Set timer to zero. And start again.
     */
    public function reset() {
        $this->time = microtime(TRUE);
    }

    public function __toString() {
        $time = $this->getTime(); //
        return sprintf($template, $time);
    }
}
?>

Viewing latest article 6
Browse Latest Browse All 23

Trending Articles