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