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