PHP Benchmarking for the Noobs

Benchmarking in programming basically means calculating the speed or execution time of an application.
The faster your application, the lesser the amount of server resources consumed by it and the more user-friendly it becomes (users love fast applications).

Using a timer, you can benchmark the speed of a database query, execution time of a given code and lots more. Doing so, you know the area in your application that is lagging.

Using PHP’s microtime Date/Time Functions, you can benchmark the performance of your web application.

As an example, I will be benchmarking a For loop.


< ?php
// store the time the code execution started
$time_start = microtime(true);

// a for loop sample
for ($i=0; $i <=5 ; $i++) { 
	echo "Looping in progress $i \n";
}

// store the time the code execution ended
$time_end = microtime(true);

// subtract to get the code execution time
$time = $time_end - $time_start;

// output the execution time in seconds to 7 decimal places
printf('Looping execution time is %.7f seconds \n', $time);
?>

To avoid repeating yourself and simplify the benchmarking process, I created the below class.


class Benchmark {
	private $_time_start;

	function start() {
		// store the time the code execution started
		$this -> _time_start = microtime(true);
	}

	function result() {
		// store the time the code execution ended
		$time_end = microtime(true);

		// subtract to get the code execution time
		$time = $time_end - $this -> _time_start;

		// output the execution time in seconds to 7 decimal places
		printf("Looping execution time is %.7f seconds \n", $time);

	}

}

To use the class;

  1. firstly, instantiate it.
  2. Call the start() method to keep record of the time the code execution started
  3. Follow by the code snippet to be tested
  4. Call the start() method to reveal the benchmark time.

Don’t forget to call the start() method for subsequent benchmarking as shown in the code below.


< ?php
$object = new Benchmark;

$object -> start();

for ($i = 0; $i < = 5; $i++) {
	echo "Looping in progress $i \n";
}

$object -> result();

// start another benchmark by calling the start method
// otherwise, result will be inaccurate

$object -> start();

usleep(100);

$object -> result();
?>
Don’t miss out!
Subscribe to My Newsletter
Invalid email address