PHP memory profiling

JW. picture JW. · May 19, 2009 · Viewed 51.4k times · Source

What's a good way to profile a PHP page's memory usage? For example, to see how much memory my data is using, and/or which function calls are allocating the most memory.

  • xdebug doesn't seem to provide memory information in its profiling feature.

  • xdebug does provide it in its tracing feature. This is pretty close to what I want, except the sheer amount of data is overwhelming, since it shows memory deltas for every single function call. If it were possible to hide calls below a certain depth, maybe with some GUI tool, that would solve my problem.

Is there anything else?

Answer

Francesco Casula picture Francesco Casula · May 21, 2014

As you probably know, Xdebug dropped the memory profiling support since the 2.* version. Please search for the "removed functions" string here: http://www.xdebug.org/updates.php

Removed functions

Removed support for Memory profiling as that didn't work properly.

So I've tried another tool and it worked well for me.

https://github.com/arnaud-lb/php-memory-profiler

This is what I've done on my Ubuntu server to enable it:

sudo apt-get install libjudy-dev libjudydebian1
sudo pecl install memprof
echo "extension=memprof.so" > /etc/php5/mods-available/memprof.ini
sudo php5enmod memprof
service apache2 restart

And then in my code:

<?php

memprof_enable();

// do your stuff

memprof_dump_callgrind(fopen("/tmp/callgrind.out", "w"));

Finally open the callgrind.out file with KCachegrind

Using Google gperftools (recommended!)

First of all install the Google gperftools by downloading the latest package here: https://code.google.com/p/gperftools/

Then as always:

sudo apt-get update
sudo apt-get install libunwind-dev -y
./configure
make
make install

Now in your code:

memprof_enable();

// do your magic

memprof_dump_pprof(fopen("/tmp/profile.heap", "w"));

Then open your terminal and launch:

pprof --web /tmp/profile.heap

pprof will create a new window in your existing browser session with something like shown below:

PHP memory profiling with memprof and gperftools

Xhprof + Xhgui (the best in my opinion to profile both cpu and memory)

With Xhprof and Xhgui you can profile the cpu usage as well or just the memory usage if that's your issue at the moment. It's a very complete solutions, it gives you full control and the logs can be written both on mongo or in the filesystem.

For more details see my answer here.

Blackfire

Blackfire is a PHP profiler by SensioLabs, the Symfony2 guys https://blackfire.io/

If you use puphpet to set up your virtual machine you'll be happy to know it's supported ;-)