Codebreaker 2bc08752a0894eb2c7afb345286e391d

19Jun/071

PHP Timer

Introduction

A timer is a very commonly used feature for various purposes such as unit tests or performance optimization. However, it is such a painful job to implement a timer every time as demanded, even though it takes only few lines of code. Here is a solution for those kind of issues.

Basic Usage

Using Timer is pretty simple. It's just like a stop watch in the real life. All we need to do is to push the start button as a sprinter does a start dash, and push the stop button as the sprinter finishes.

Timer::start();

// sprint!

Timer::end();
Timer::display();

The following or similar message will be displayed by default if no argument is given at display() method.

This page was created in 0.007 seconds.

Advanced Usage

We can easily change the message by giving an argument.

Timer::display('It has been %.5f sec');

Then it will display the following.

It has been 0.00719 sec

Also, we can change the time unit.

Timer::display('This page was created in %d ms.', 1000);

The second argument mutiplies the duration, which is given in seconds, by itself. As a result, the time unit will be milliseconds instead of seconds.

This page was created in 7 ms.

Similarly, if you put 1,000,000 or even 1,000,000,000 then the time unit will be microseconds and nanoseconds, respectively. However, there is no guarantee that the timer provides such accuracy.

Restrictions

This Timer class is not designed for nested multiple timers on a single page. (i.e. Once a timer starts, we can't start the timer before we stop the timer. Otherwise, it wouldn't work properly) However, we can easily change it by removing static keywords, and substituting self keyword with this so that we can generate multiple timers. Also, we can add a constructor as necessary. Now, we're gonna have to make an actual instance of Timer to be able to use it.

Full Source

<?php
/**
 * @since 20070619
 * @version 20070619
 * @author Sumin Byeon
 * @copyright Copyright (c) 2003-2007 SBBS Team
 */
class Timer {

    private static $start;
    private static $end;

    public static function start() {
        self::$start = microtime(true);
    }

    public static function end() {
        self::$end = microtime(true);
    }

    public static function getDuration() {
        return self::$end - self::$start;
    }

    public static function display($message = 'This page was created in %.3f seconds.<br/>', $multiplier=1) {
        printf($message, self::getDuration()*$multiplier);
    }
}
?>

References

Tagged as: Leave a comment
Comments (1) Trackbacks (0)
  1. PHP는 echoprint는 키워드라서 메서드 이름으로 하지 못하기 때문에 항상 display 같이 다른 메서드 이름을 찾아야 하는게 좀 짜증나죠.


Leave a comment


No trackbacks yet.