Project

General

Profile

PHP Profiling » History » Version 3

Carsten Rose, 06.01.2024 14:11

1 1 Carsten Rose
h1. PHP Profiling
2
3
h2. xdebug
4
5 2 Carsten Rose
* https://xdebug.org/docs/profiler
6 3 Carsten Rose
* "Xdebug 3":https://www.youtube.com/playlist?list=PLg9Kjjye-m1g_eXpdaifUqLqALLqZqKd4 (youtube)
7 2 Carsten Rose
8 1 Carsten Rose
h2. via php
9
10
No extensions are needed, just use these two functions for simple profiling.
11
12
<pre>
13
// Call this at each point of interest, passing a descriptive string
14
function prof_flag($str)
15
{
16
    global $prof_timing, $prof_names;
17
    $prof_timing[] = microtime(true);
18
    $prof_names[] = $str;
19
}
20
21
// Call this when you're done and want to see the results
22
function prof_print()
23
{
24
    global $prof_timing, $prof_names;
25
    $size = count($prof_timing);
26
    for($i=0;$i<$size - 1; $i++)
27
    {
28
        echo "<b>{$prof_names[$i]}</b><br>";
29
        echo sprintf("&nbsp;&nbsp;&nbsp;%f<br>", $prof_timing[$i+1]-$prof_timing[$i]);
30
    }
31
    echo "<b>{$prof_names[$size-1]}</b><br>";
32
}
33
</pre>
34
35
Here is an example, calling prof_flag() with a description at each checkpoint, and prof_print() at the end:
36
37
<pre>
38
prof_flag("Start");
39
40
   include '../lib/database.php';
41
   include '../lib/helper_func.php';
42
43
prof_flag("Connect to DB");
44
45
   connect_to_db();
46
47
prof_flag("Perform query");
48
49
   // Get all the data
50
51
   $select_query = "SELECT * FROM data_table";
52
   $result = mysql_query($select_query);
53
54
prof_flag("Retrieve data");
55
56
   $rows = array();
57
   $found_data=false;
58
   while($r = mysql_fetch_assoc($result))
59
   {
60
       $found_data=true;
61
       $rows[] = $r;
62
   }
63
64
prof_flag("Close DB");
65
66
   mysql_close();   //close database connection
67
68
prof_flag("Done");
69
prof_print();
70
</pre>
71
72
Output looks like this:
73
74
<pre>
75
Start
76
   0.004303
77
Connect to DB
78
   0.003518
79
Perform query
80
   0.000308
81
Retrieve data
82
   0.000009
83
Close DB
84
   0.000049
85
Done
86
</pre>