How to Measure the Speed of Code Written in PHP

How can I measure the speed of code written in 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 !

Accurate way to measure execution times of php scripts

You can use the microtime function for this. From the documentation:

microtime — Return current Unix timestamp with microseconds



If get_as_float is set to TRUE, then microtime() returns a float, which represents the current time in seconds since the Unix epoch accurate to the nearest microsecond.

Example usage:

$start = microtime(true);
while (...) {

}
$time_elapsed_secs = microtime(true) - $start;

How to measure the download speed and size of a PHP document

ob_get_clean() will return a string. To obtain the number of bytes write

$sebesseg = ob_get_clean();
$numberOfBytes = strlen($sebesseg);

After reading your last comment, I've preapred a short example how a simple download speed measurement script can be done with PHP. The following code should do what you want:

<?php
// get the start time as UNIX timestamp (in millis, as float)
$tstart = microtime(TRUE);

// start outout buffering
ob_start();

// display your page
include 'some-page.php';

// get the number of bytes in buffer
$bytesWritten = ob_get_length();

// flush the buffer
ob_end_flush();

// how long did the output take?
$time = microtime(TRUE) - $tstart;

// convert to bytes per second
$bytesPerSecond = $bytesWritten / $time;

// print the download speed
printf('<br/>You\'ve downloaded %s in %s seconds',
humanReadable($bytesWritten), $time);
printf('<br/>Your download speed was: %s/s',
humanReadable($bytesPerSecond));

/**
* This function is from stackoverflow. I just changed the name
*
* http://stackoverflow.com/questions/2510434/php-format-bytes-to-kilobytes-megabytes-gigabytes
*/
function humanReadable($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');

$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);

// Uncomment one of the following alternatives
//$bytes /= pow(1024, $pow);
$bytes /= (1 << (10 * $pow));

return round($bytes, $precision) . ' ' . $units[$pow];
}

Note that the real download speed can only measured at the client. But the results from the code above should be approximately ok.

Also it would just measure the download size of the HTML page itself. Images. styles and javascripts will extend the real download size of page load. But the speed should be in most cases the same the HTML document.

best way to measure (and refine) performance with PHP?

If you want to test the execution time :

<?php
$startTime = microtime(true);
// Your content to test
$endTime = microtime(true);
$elapsed = $endTime - $startTime;
echo "Execution time : $elapsed seconds";
?>

How to measure speed of php scripts independantly of eachother? Various Methods?

No defualt method i can thnik of. But its easy.At the start of your script simply place this:

$s = microtime(true);

and at the end

$e = microtime(true);
echo round($e - $s, 2) . " Sec";

Normally you would leave the second parameter of round() as it is, but if you find that your script reports the time as ’0 Sec’ increase the number until you get an answer.check this for more

measuring the elapsed time between code segments in PHP

A debugger like XDebug/Zend Debugger can give you this type of insight (plus much more), but here is a hint at how you can write a function like that:

function time_elapsed()
{
static $last = null;

$now = microtime(true);

if ($last != null) {
echo '<!-- ' . ($now - $last) . ' -->';
}

$last = $now;
}

Mainly the function microtime() is all you need in order to do the time calculations. To avoid a global variable, I use a static variable within the elapsed function. Alternatively, you could create a simple class that can encapsulate the required variables and make calls to a class method to track and output the time values.

PHP code's performance test

xDEBUG (see Neil Aitken's answer) is useful for identifying poor performance issues in PHP code - but it can only be used under very controlled and restrictive conditions - not least its difficult to see what effect concurency has on the performance.

While as Patrick MARIE suggests, you could use ab - its not a viable approach if the transaction you are trying to measure spans more than page (e.g. log in to application and create session, add a random product to basket, repeat add random product N times...).

AFAIK there's no PHP based solution for recording/scripting interactions - but there is Perl + WWW:Mechanize + HTTP:recorder. Or if you're extremely rich you could buy HPs loadrunner product.

But its very difficult to implement testing which is truly representative of how the application is used - and the performance of the application (at least the data related parts) will vary over time - so you need to build proper performance metrics into your code.

...and even then, the time taken for the PHP to generate an HTML page is only a very small part of the story of how long it takes for a page to render on the browser.

HTH

C.

Tracking the script execution time in PHP

On unixoid systems (and in php 7+ on Windows as well), you can use getrusage, like:

// Script start
$rustart = getrusage();

// Code ...

// Script end
function rutime($ru, $rus, $index) {
return ($ru["ru_$index.tv_sec"]*1000 + intval($ru["ru_$index.tv_usec"]/1000))
- ($rus["ru_$index.tv_sec"]*1000 + intval($rus["ru_$index.tv_usec"]/1000));
}

$ru = getrusage();
echo "This process used " . rutime($ru, $rustart, "utime") .
" ms for its computations\n";
echo "It spent " . rutime($ru, $rustart, "stime") .
" ms in system calls\n";

Note that you don't need to calculate a difference if you are spawning a php instance for every test.

PHP Get Page Load Stats - How to measure php script execution / load time

microtime() returns the current Unix timestamp with microseconds. i don't see any math there that does the conversion from microseconds to seconds.

microtime(true) returns the time as a float in seconds



Related Topics



Leave a reply



Submit