CodeBlanks Logo Icon CodeBlanks

Profiling tools

PHP course · Expert · Lesson 23/54

Learn to profile and find bottlenecks with Xdebug and XHProf.

What is profiling for?

Profiling measures where running code spends time. It is not debugging — it is bottleneck hunting. Xdebug gives step tracing and stack traces during development, while XHProf produces a function call graph with low overhead, suitable for production-like runs.

The output lists each function's call count (ct), wall time (wt) and CPU time (cpu). The hot path is the chain of calls that consumes the most time; you read a profile by following it.

Call graph and hot path

A profile report can be turned into a call graph that shows how functions call each other. Nodes are functions, edges are the called from relation. The hot path is the root-to-leaf chain with the highest total time.

XHProf's raw data is enough to rebuild this graph; functions with high call count (ct) but low wall time (wt) are not the target — the chain where wt accumulates is. Sort by total wt to avoid chasing the wrong target.

Exercise Check XHProf availability

Check 'xhprof_enable' with function_exists. If present call xhprof_enable(), run str_repeat('a', 1000), collect $data = xhprof_disable() and print echo count($data) . "\n". Otherwise print echo "XHProf not installed\n".

Show example solution
If function_exists('xhprof_enable') is true call xhprof_enable(); str_repeat('a', 1000); $data = xhprof_disable(); echo count($data) . "\n";. In the else branch echo "XHProf not installed\n";.
Example solution:
<?php
if (function_exists('xhprof_enable')) {
    xhprof_enable();
    str_repeat('a', 1000);
    $data = xhprof_disable();
    echo count($data) . "\n";
} else {
    echo "XHProf not installed\n";
}

Test yourself

  1. Complete the xhprof_enable call

    ____(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
    $data = xhprof_disable();
    Show answer
    xhprof_enable(XHPROF_FLAGS_CPU | XHPROF_FLAGS_MEMORY);
    $data = xhprof_disable();
  2. Why does XHProf's low overhead matter?

    • So it can run in production-like conditions
    • To make debugging easier
    • To write less code
    • To hide stack traces
    Show answer

    So it can run in production-like conditions — Correct. Low overhead lets you profile in production-like conditions.

  3. Match the profiling concepts

    ct
    Call count
    wt
    Wall time
    hot path
    Slowest call chain
    Xdebug
    Step tracing

All lessons in Expert