phpprofiling

Simplest way to profile a PHP script


What's the easiest way to profile a PHP script?

I'd love tacking something on that shows me a dump of all function calls and how long they took, but I'm also OK with putting something around specific functions.

I tried experimenting with the microtime function:

$then = microtime();
myFunc();
$now = microtime();

echo sprintf("Elapsed:  %f", $now-$then);

But that sometimes gives me negative results. Plus it's a lot of trouble to sprinkle that all over my code.


Solution

  • The PECL APD extension is used as follows:

    <?php
    apd_set_pprof_trace();
    
    // The rest of the script
    ?>
    

    After, parse the generated file using pprofp.

    Example output:

    Trace for /home/dan/testapd.php
    Total Elapsed Time = 0.00
    Total System Time  = 0.00
    Total User Time    = 0.00
    
    
    Real         User        System             secs/    cumm
    %Time (excl/cumm)  (excl/cumm)  (excl/cumm) Calls    call    s/call  Memory Usage Name
    --------------------------------------------------------------------------------------
    100.0 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0000   0.0009            0 main
     56.9 0.00 0.00  0.00 0.00  0.00 0.00     1  0.0005   0.0005            0 apd_set_pprof_trace
     28.0 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 preg_replace
     14.3 0.00 0.00  0.00 0.00  0.00 0.00    10  0.0000   0.0000            0 str_replace
    

    Warning: the latest release of APD is dated 2004. The extension is no longer maintained and has various compatibility issues (see comments).