This article is more than ten years old and potentially contains out-dated information.
작성한지 10년 이상 지난 게시물입니다. 최신의 정보와 맞지 않는 내용을 포함할 수도 있습니다.

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