nabeel shahzad

Profiling PHP Code

with 2 comments

After or during writing a project, it’s important to visit your code with a profiler – see how long your code takes to run, and identify potential bottlenecks, and places where you can improve your code.

The profiler I use is Xdebug, a slick PHP debugger, and profiling tool. I use XAMPP for my testing (no running services, turn on Apache and MySQL when I need it), on my machine, and it comes with the xdebug extension by default. I leave xdebug enabled, as it gives great debugging information, including a caller/stack trace. You also need a program called WinCacheGrind, which will allow you to view the profile traces.

To enable Xdebug in your XAMPP config, go to: C:\xampp\apache\bin (I installed it in C:\xampp), and open up your php.ini file, and go down to the “extensions”, and uncomment this line:

[code]
;extension=php_xdebug.dll
[/code]

So it reads:

[code]
extension=php_xdebug.dll
[/code]

And then add this at the bottom of your .ini file (Note: your php.ini file may already have this, just needs to be uncommented)

[code]
[XDebug]
;; Only Zend OR (!) XDebug
zend_extension_ts="C:\xampp\php\ext\php_xdebug.dll"
xdebug.remote_enable=true
xdebug.remote_host=127.0.0.1
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
xdebug.profiler_enable=1
xdebug.profiler_output_dir="C:\xampp\tmp"
[/code]

This will enable the profiler, as well as the debugging. Restart Apache in the XAMPP control panel, and run a single PHP page (ie, I goto http://localhost/phpvms). Just run it once, and goto your C:\xampp\tmp directory. There will be a file like “cachegrind.out.<number>”. Open this file using WinCacheGrind, and you’ll see something similar to:

cache

I’ve expanded it out, but you can see the time it takes to run each function, load any include()’s, etc. This is a great way to peek into your scripts and see what’s going on in there, and where you can concentrate your optimization efforts. I’ll share some of the things I did to optimize in the future.

Written by Nabeel

December 18th, 2008 at 11:16 am

Posted in General

  • Sara M.

    This seriously is so useful
    Thank You Nabeel :)

  • http://flyzenvirtual.blogspot.com Jacob Krustchinsky

    Wow Im loving how easy this is to set up and how useful i have found it when building on CODON.