Pro PHP- Patterns, Frameworks, Testing and More

(vip2019) #1
CHAPTER 8 ■ TESTING, DEPLOYMENT, AND CONTINUOUS INTEGRATION^123

Profiling with Xdebug.


You can use the following functions to get profile information:

int xdebug_memory_usage(): This function returns the current memory usage at the time
the function is called.

int xdebug_peak_memory_usage(): This function returns the greatest amount of memory
the script has used from script startup until the time the function is called.

float xdebug_time_index(): This function returns the time in seconds since the script
began running. It’s very precise and will allow you to track down slow sections of code.

Xdebug also ships with an application-wide profiler that saves information about which
functions were called during execution and how many times each was called. To enable this
profiler, add the following to your php.ini file:

xdebug.profiler_enable=1
xdebug.profiler_output_dir=/path/you/want/profile/file/placed

This enables the profiler to start saving information. To read the information, you will
need an analyzer like KCacheGrind or WinCacheGrind.

■Caution Use the application-wide profiler feature only when necessary, as it will add significant overhead
to your PHP scripts. Additionally, the profile files can use up significant amounts of disk space.

Checking Code Coverage with Xdebug


It is often useful to know how effective your library organization is. Theoretically, if only a fraction
of the code in a given file is commonly executed, you may get some performance gain by
breaking up the file into two or more files. However, as with all performance optimization, it is
important not to get carried away. Code coverage can also help you identify if code never gets
called and is simply dead or inaccessible.
The code-coverage functionality provided by Xdebug comes in the form of a function that
tells you exactly which lines of a file have been run during any given execution, as well as functions
to pause and get code coverage:

void xdebug_start_code_coverage( [int options] ): This function begins collecting
code-coverage information. It has two options: XDEBUG_CC_UNUSED and XDEBUG_CC_DEAD_
CODE, both of which can be used to determine if code is callable.

void xdebug_stop_code_coverage( ): This function pauses the collection of code-coverage
data.

array xdebug_get_code_coverage( ): This function returns a multidimensional array, where
the format is $array[filename][line] = numberofcalls;

McArthur_819-9C08.fm Page 123 Friday, February 22, 2008 9:06 AM

Free download pdf