Project

General

Profile

PHP Profiling » History » Version 5

Carsten Rose, 06.01.2024 14:14

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