views:

155

answers:

5

What is the best way for test my php code's performance?

+2  A: 

You can use time() to messure the execution time of your code. Here is a basic code snippet for that:

$start_timestamp = time();
...
---your Code---
...
$end_timestamp = time();
$duration = $end_timestamp - $start_timestamp;
error_log("Execution took ".$duration." milliseconds.");
Thariama
+4  A: 

You should consider using ab (apache benchmark tool) to run a large number of queries and xhprof to profile/analyse your code. In my opinion, these just are the basics but give great results.

Patrick MARIE
+4  A: 

xDebug has a profiler built in, once configured it will dump some files that you can read with a program like kCacheGrind or WinCacheGrind

This will then allow you to see the all the function calls, average and cumulative call times and the total script execution time. Very helpful for finding bottlenecks in your code.

Neil Aitken
A: 

If you want to test a specific part of the code, consider using the Benchmark package from the PHP PEAR library.

$timer = new Benchmark_Timer();
$timer->start();
// Code to test here
$timer->stop();
$timer->display();
chiborg
+1  A: 

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.

symcbean
Very nicely put, it's difficult to measure how your app may perform under heavy load. You can use Selenium instead of Mechanize to automate browsers, but as far as I know it's not designed for load testing.
Neil Aitken