How do I profile my PHP script performance on OSX?

Sounds easy eh? Well it is but i had to face some challenges to get things to work. And sharing is caring right ha! (sarcastic laughter*)

The fast fast way

If you don't have Xdebug installed and just wan't to short test how much time something inside your scripty script consumes, you could go the php way. Lets be honest it doesn't happen really often in the daily PHP life that you have to profile a script so in many cases the fast fast way ain't too bad.

I wrote a really simple class, that I basically just copy paste inside my script if I need to really shortly benchmark something:

Usage then is simple:

Benchi::check('Step 1');  
Benchi::check('Stepchen 2');  
Benchi::check('Step 3');

echo Benchi::draw();  

I also can recommend the hoa/bench library if you are looking for something more approved.


The better way.

Now lets come to the good part. The XDebug profiler is great if need more detail. So make sure XDebug is installed.

Now enable the xdebug.profiler_enable_trigger setting in your php.ini if you haven't already.

How to find PHP.ini

Now if you are an idiot like me you keep forgetting where the hell the php.ini is stored on your system. But hey there is a way to find that out!

$ php -i | grep php.ini

I love that command so much...

Enable profiler trigger

Now open up that ini file (in my case under: /usr/local/etc/php/5.6/php.ini) and add the xdebug setting at the end.

xdebug.profiler_enable_trigger = 1  

Profiling a script

With the xdebug.profiler_enable_trigger setting enabled you can profile your script by passing the XDEBUG_PROFILE parameter via GET, POST or as a cookie.

curl 'http://localhost/?XDEBUG_PROFILE=1'  

If you wan't to profile a script on the command line you can enable the profiler manually:

$ php -d xdebug.profiler_enable=On <yourphpscrip>.php

Viewing the results

Now Xdebug has generated a cachegrind file. Don't know where? By default the files are stored at: /var/tmp/. But you can find your system specific directory with another amazing command:

$ php -i | grep xdebug.profiler_output_dir

<3 grep <3

Now there are 2 clients I know that will work on OSX to analyse the cachegrind files.

1. Webgrind

Webgrind on Github

Webgrind is php based, so the amazing thing about that is there is no installation needed. Just clone the source and create a PHP Server inside it:

$ php -S localhost:8080

2. qcachegrind

qcachegrind on Sourceforge

If you prefer a real desktop client this is the way to go. qcachegrind is available on homebrew so the installation is also not more than one command.

$ brew install qcachegrind

Now you can open your file just like this:

$ qcachegrind path/to/cachegrind.out.34534
Mario Döring

Mario Döring

Software Engineer, ClanCats Dude, Developer and general Idiot.

View Comments