Page 1 of 1

PHP Timing Class

Posted: Mon Oct 09, 2006 2:28 am
by s.dot
Nothing fancy here...

The Code

Code: Select all

<?php

/*
* This class will calculate time in seconds for 
* timing script or function execution times
* Author - scottayy@gmail.com
*/

class timer
{
	var $time_start;
	var $time_end;
	var $round_to = 5;
	
	function start_timer()
	{
		$this->time_start = $this->microtime_float();
	}
	
	function stop_timer()
	{
		$this->time_end = $this->microtime_float();
	}
	
	function calculate_time()
	{
		return round($this->time_end - $this->time_start, $this->round_to);
	}
	
	function microtime_float()
	{
		if(version_compare('5.0.0',phpversion()))
		{
			return microtime(1);
		} else
		{
			list($usec, $sec) = explode(" ", microtime());
			return ((float)$usec + (float)$sec);
		}
	}
	
}

?>
Usage

Code: Select all

$timer = new timer();
$timer->start_timer();

for($i=0;$i<1000000;$i++)
{
	//do nothing.. or something?
}

$timer->stop_timer();
echo $timer->calculate_time();
Output

Code: Select all

0.11116

Posted: Mon Oct 09, 2006 3:39 am
by Chris Corbyn
I have something like this too for calculating page execution times (a little note I add to the footer).

Dead simple... never thought to check if PHP already can give the value as a float:

Code: Select all

<?php

/**
 * Logs the amount of time taken from instantiation to getDuration()
 * @package XXXXXX
 * @author Chris Corbyn
 */
class PageTimer
{
	/**
	 * The time in microseconds at instantiation
	 * @var float time
	 */
	private $start = 0;
	
	/**
	 * Constructor
	 */
	public function __construct()
	{
		$this->start = $this->getMicrotimeAsFloat();
	}
	/**
	 * Get the time from $start to now()
	 * @param int decimal places
	 * @return float
	 */
	public function getDuration($round=3)
	{
		return round($this->getMicrotimeAsFloat() - $this->start, $round);
	}
	/**
	 * Process the output of microtime() to get a float
	 * @return float
	 */
	private function getMicrotimeAsFloat()
	{
		$parts = explode(' ', microtime());
		return (float) $parts[0] + (float) $parts[1];
	}
}
It can also be registered and used for finding bottlenecks.