Tuesday, April 3, 2012

Profiling PHP Code

Time Profiling PHP Code: this is how to get your PHP code profiled with xdebug, Fedora and httpd.  Concepts might stretch to other platforms.

1) Install xdebug

sudo yum install php-pecl-xdebug

2) Under /etc/php.ini Options, add in the following line:

zend_extension = /usr/lib64/php/modules/xdebug.so

3) In /etc/httpd/conf/httpd.conf, change the following:

<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

to this

<Directory />
    Options FollowSymLinks
#    AllowOverride None
    AllowOverride All
</Directory>


4) Also put in the AllowOverride All command in the following place:

#
# This should be changed to whatever you set DocumentRoot to.
#
<Directory "/var/www/html">

    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.2/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   Options FileInfo AuthConfig Limit
    #
#    AllowOverride None
    AllowOverride All


5) Perform the following permissions change:

sudo chmod -R 777 /var/lib/php/session

6) In the PHP code directory that you want to profile, create a .htaccess file and add in the following:

php_value xdebug.profiler_enable 1
php_value xdebug.profiler_output_dir /tmp

7) Restart httpd

sudo /sbin/service/httpd restart

8) You'll need kcachegrind to visualize the profiling output.  Download and compile it. 

8a) Get the source from here: http://kcachegrind.sourceforge.net/html/Download.html

8b) tar -zxvf kcachegrind-0.7.1.tgz

8c) sudo yum install kdebase-devel

8d) cd kcachegrind-0.7.1

8e) mkdir build

8f) cd build

8g) ccmake ..

8h) All the defaults are fine, but you can change the CMAKE_BUILD_TYPE to Debug

8i) make -j12

8j) sudo make install

9) Now, run your PHP script.  The results are either in /tmp or /tmp/systemd-private-*/tmp and you can visualize them with the /usr/local/bin/kcachegrind cachegrind.out.1234.

If you run into problems, you might find hints in/var/log/httpd/error_log.  Or, you can try to run your php script on the command line, e.g.:

$ php index.php

1 comment:

Vivek said...

Hey, thanks for this post. actually I was looking this for my new project so thanks again.
Hire Magento Developer