Easy Benchmarking class

When working to optimize either your own or someone else’s PHP code, it can be very useful to find out where the most time is being spent. This is especially true with long running cron scripts.

It’s pretty easy to do on a case-by-case basis, but after years of programming and writing the code to accomplish this, I decided it was easier to just create a Bench class.

The point of the Bench class is to allow me to add multiple data points throughout the code, and to show me the results upon completion of the script. I tried to make it as least obstructive as possible.

Please feel free to use and share this code as desired. If you run into any problems, or have any issues, let me know.

Bench.php Source Code:

<?php
/*
* author sgricci
* access public
* license gpl
* website http://deepcode.net
*/
class Bench {
	private $points = array();
	private $start;
 
	public function __construct() {
		$this->start = $this->utime();
	}
 
	private function utime()
	{
		$time = explode(" ", microtime());
		$usec = (double) $time[0];
		$sec = (double) $time[1];
		return ($sec + $usec);
	}
 
	public function pt($name = "")
	{
		if (!$name)
			$this->points[] = $this->utime();
		else
			$this->points[$name] = $this->utime();
	}
 
	public function __destruct()
	{
		$this->pt("total");
		foreach ($this->points as $name => $pt)
		{
			echo $name.": ".round(abs($this->start - $pt),4)."\n";
		}
	}
}
?>

Usage:

<?php
require_once "Bench.php";
$B = new Bench(); # Place at the beginning of the script.
// process some queries and then call
$B->pt("post-query process");
// process the data from the queries and then call
$B->pt("post-data process");
// go on with the rest of your script
?>

Posted in PHP, benchmarking, code, optimizing at February 27th, 2009. No Comments.