How can I measure the speed of code written in PHP?

PhpTestingPerformanceMeasurement

Php Problem Overview


How can I say which class of many (which all do the same job) execute faster? is there a software to measure that?

Php Solutions


Solution 1 - Php

You have (at least) two solutions :

The quite "naïve" one is using microtime(true) tobefore and after a portion of code, to get how much time has passed during its execution ; other answers said that and gave examples already, so I won"t say much more.

This is a nice solution if you want to benchmark a couple of instructions ; like compare two types of functions, for instance -- it's better if done thousands of times, to make sure any "perturbating element" is averaged.

Something like this, so, if you want to know how long it take to serialize an array :

$before = microtime(true);

for ($i=0 ; $i<100000 ; $i++) {
    serialize($list);
}

$after = microtime(true);
echo ($after-$before)/$i . " sec/serialize\n";

Not perfect, but useful, and it doesn't take much time to set up.



The other solution, that works quite nice if you want to identify which function takes lots of time in an entire script, is to use :

  • The Xdebug extension, to generate profiling data for the script
  • Software that read the profiling data, and presents you something readable. I know three of those :
    • Webgrind ; web interface ; should work on any Apache+PHP server
    • WinCacheGrind ; only on windows
    • KCacheGrind ; probably only Linux and linux-like ; That's the one I prefer, btw

To get profiling files, you have to install and configure Xdebug ; take a look at the Profiling PHP Scripts page of the documentation.

What I generally do is not enable the profiler by default (it generates quite big files, and slows things down), but use the possibility to send a parameter called XDEBUG_PROFILE as GET data, to activate profiling just for the page I need.
The profiling-related part of my php.ini looks like this :

xdebug.profiler_enable = 0              ; Profiling not activated by default
xdebug.profiler_enable_trigger = 1      ; Profiling activated when requested by the GET parameter
xdebug.profiler_output_dir = /tmp/ouput_directory
xdebug.profiler_output_name = files_names

(Read the documentation for more informations)

This screenshot is from a C++ program in KcacheGrind : http://kcachegrind.sourceforge.net/html/pics/KcgShot3Large.gif
(source: sourceforge.net)

You'll get exactly the same kind of thing with PHP scripts ;-)
(With KCacheGrind, I mean ; WinCacheGrind is not as good as KCacheGrind...)

This allows you to get a nice view of what takes time in your application -- and it sometimes definitly helps to locate the function that is slowing everything down ^^

Note that Xdebug counts the CPU time spent by PHP ; when PHP is waiting for an answer from a Database (for instance), it is not working ; only waiting. So Xdebug will think the DB request doesn't take much time !
This should be profiled on the SQL server, not PHP, so...


Hope this is helpful :-)
Have fun !

Solution 2 - Php

For quick stuff I do this (in PHP):

$startTime = microtime(true);
doTask(); // whatever you want to time
echo "Time:  " . number_format(( microtime(true) - $startTime), 4) . " Seconds\n";

You can also use a profiler like [http://xdebug.org/][1].

[1]: http://xdebug.org/ "xdebug"

Solution 3 - Php

I've made a simple timing class, maybe it's useful to someone:

class TimingHelper {
	
	private $start;
	
	public function __construct() {
		$this->start = microtime(true);
	}
	
	public function start() {
		$this->start = microtime(true);
	}
	
	public function segs() {
		return microtime(true) - $this->start;
	}
	
	public function time() {
		$segs = $this->segs();
		$days = floor($segs / 86400);
		$segs -= $days * 86400;
		$hours = floor($segs / 3600);
		$segs -= $hours * 3600;
		$mins = floor($segs / 60);
		$segs -= $mins * 60;
  		$microsegs = ($segs - floor($segs)) * 1000;
 		$segs = floor($segs);
		
		return 
			(empty($days) ? "" : $days . "d ") . 
			(empty($hours) ? "" : $hours . "h ") . 
			(empty($mins) ? "" : $mins . "m ") . 
			$segs . "s " .
			$microsegs . "ms";
	}
	
}

Use:

$th = new TimingHelper();
<..code being mesured..>
echo $th->time();
$th->start(); // if it's the case
<..code being mesured..>
echo $th->time();

// result: 4d 17h 34m 57s 0.00095367431640625ms 

Solution 4 - Php

2020 Update

It's been many years since I last answered this questions so I thought this deserves an update on the APM landscape.

  • AppDynamics has been bought by Cisco and free forever account they used to offer has been taken out from their website.
  • NewRelic has dropped their pricing from $149/month/host to $25/month/host to compete with the new comer to the APM market, Datadog which offers $31/month/host.
  • Datadog APM features are still light and leaves much to be desired for. However, I see them enhancing and improving these throughout the next year.
  • Ruxit has been bought by Dynatrace. No shocker here as Ruxit is built by ex Dynatrace Employees. This allowed Dynatrace to transform to a truly SaaS model for better. Say goodbye to that bulky Java client if you'd like to.
  • There are free/open-source options now as well. Checkout Apache Skywalking which is very popular in China among their top tech companies and PinPoint which offers a demo that you can try before installing. Both of these require you manage hosting so get ready to spin up few Virtual Machine and spend some time with installation and configuration.
  • I haven't tried either of these opensource APM solution so I'm in no position to recommend them, however, I've personally managed deploying all of these APM solutions for multiple organizations either on-premise or on cloud for hundreds of application/microservices. So I can say with confidence, you can't go wrong with any of the vendors if they fit your bill.


Originally Answered on October 2015

Here is a direct answer to your question

> is there a software to measure that?

Yes, there is. I'm wondering why anyone hasn't mentioned it yet. Although the answers suggested above seems fine for a quick check but isn't scalable in the long run or for a bigger project.

Why not use an Application Performance Monitoring (APM) tool which are build exactly for that and so much more. Check out NewRelic, AppDynamics, Ruxit (all have free version) to monitor the execution time, resource usage, throughput of every application to the method level.

Solution 5 - Php

If you want to quick test performance of a framework, you can put in index.php file

//at beginning
$milliseconds = round(microtime(true) * 1000);

//and at the end
echo round(microtime(true) * 1000) - $milliseconds;

Every time you will get execution time in milliseconds. Because microseconds is not too useful in testing a framework case.

Solution 6 - Php

I've been using XHProf lately http://pecl.php.net/package/xhprof. It was originally developed by Facebook and it comes with a decent web interface.

Solution 7 - Php

I'd like to share with you a self made function I use to measure the speed of any existing function up to 10 arguments:

function fdump($f_name='', $f_args=array()){

	$f_dump=array();
	$f_result='';

	$f_success=false;
	
	$f_start=microtime();
	$f_start=explode(' ', $f_start);
	$f_start=$f_start[1] + $f_start[0];

	if(function_exists($f_name)){

		if(isset($f_args[0])&&is_array($f_args[0])){
			if($f_result=$f_name($f_args)){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[1])){
			if($f_result=$f_name($f_args[0])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[2])){
			if($f_result=$f_name($f_args[0],$f_args[1])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[3])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[4])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[5])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[6])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[7])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[8])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[9])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7],$f_args[8])){
				$f_success=true;
			}
		}
		elseif(!isset($f_args[10])){
			if($f_result=$f_name($f_args[0],$f_args[1],$f_args[2],$f_args[3],$f_args[4],$f_args[5],$f_args[6],$f_args[7],$f_args[8],$f_args[9])){
				$f_success=true;
			}
		}
	}
	$f_end=microtime();
	$f_end=explode(' ', $f_end);
	$f_end=$f_end[1] + $f_end[0];
	
	$f_time=round(($f_end - $f_start), 4);
	$f_dump['f_success']=$f_success;
	$f_dump['f_time']=$f_time;
	$f_dump['f_result']=$f_result;

	var_dump($f_dump);exit;

	//return $f_result;

}

Example

function do_stuff($arg1='', $arg2=''){
	return $arg1.' '.$arg2;
}

fdump('do_stuff',array('hello', 'world'));

Returns

  array(3) {
    ["f_success"]=>
    bool(true)
    ["f_time"]=>
    float(0)            //too fast...
    ["f_result"]=>
    string(11) "hello world"
  }

Solution 8 - Php

If it's something that can be tested outside the Web context, I just use the Unix time command.

Solution 9 - Php

Zend Studio has built in support for profiling using XDebug or ZendDebugger. It will profile your code, telling you exactly how long every function took. It's a fantastic tool for figuring out where your bottlenecks are.

Solution 10 - Php

You can use basic stuff like storing timestamps or microtime() before and after an operation to calculate the time needed. That's easy to do, but not very accurate. Maybe a better solution is Xdebug, i've never worked with it but it seems to be the best-known PHP debugger/profiler I can find.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionM. A. KishawyView Question on Stackoverflow
Solution 1 - PhpPascal MARTINView Answer on Stackoverflow
Solution 2 - PhpScott SaundersView Answer on Stackoverflow
Solution 3 - PhpNelson TeixeiraView Answer on Stackoverflow
Solution 4 - Phpna-98View Answer on Stackoverflow
Solution 5 - PhptasmaniskiView Answer on Stackoverflow
Solution 6 - PhpJasonView Answer on Stackoverflow
Solution 7 - PhpRafaSashiView Answer on Stackoverflow
Solution 8 - PhpchaosView Answer on Stackoverflow
Solution 9 - PhpAllie the IconView Answer on Stackoverflow
Solution 10 - PhpAlexView Answer on Stackoverflow