Completed
Branch FET-10486-add-timestamp-checki... (611b15)
by
unknown
105:07 queued 90:18
created

Benchmark::displayResults()   C

Complexity

Conditions 8
Paths 21

Size

Total Lines 44
Code Lines 36

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 36
nc 21
nop 1
dl 0
loc 44
rs 5.3846
c 0
b 0
f 0
1
<?php
2
3
namespace EventEspresso\core\services;
4
5
defined('EVENT_ESPRESSO_VERSION') || exit;
6
7
8
9
/**
10
 * Class Benchmark
11
 * Useful for measuring the performance of a block of code
12
 *
13
 * @package       Event Espresso
14
 * @author        Brent Christensen
15
 * @since         $VID:$
16
 */
17
class Benchmark
18
{
19
20
    /**
21
     * array containing the start time for the timers
22
     */
23
    private static $start_times;
0 ignored issues
show
Unused Code introduced by
The property $start_times is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
24
25
    /**
26
     * array containing all the timer'd times, which can be outputted via show_times()
27
     */
28
    private static $times = array();
0 ignored issues
show
Unused Code introduced by
The property $times is not used and could be removed.

This check marks private properties in classes that are never used. Those properties can be removed.

Loading history...
29
30
    /**
31
     * @var array
32
     */
33
    protected static $memory_usage = array();
34
35
36
37
    /**
38
     * whether to benchmark code or not
39
     */
40
    public static function doNotRun()
41
    {
42
        return ! WP_DEBUG || (defined('DOING_AJAX') && DOING_AJAX);
43
    }
44
45
46
47
    /**
48
     * resetTimes
49
     */
50
    public static function resetTimes()
51
    {
52
        Benchmark::$times = array();
53
    }
54
55
56
57
    /**
58
     * Add Benchmark::startTimer() before a block of code you want to measure the performance of
59
     *
60
     * @param null $timer_name
61
     */
62
    public static function startTimer($timer_name = null)
63
    {
64
        if (Benchmark::doNotRun()) {
65
            return;
66
        }
67
        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
68
        Benchmark::$start_times[$timer_name] = microtime(true);
69
    }
70
71
72
73
    /**
74
     * Add Benchmark::stopTimer() after a block of code you want to measure the performance of
75
     *
76
     * @param string $timer_name
77
     */
78
    public static function stopTimer($timer_name = '')
79
    {
80
        if (Benchmark::doNotRun()) {
81
            return;
82
        }
83
        $timer_name = $timer_name !== '' ? $timer_name : get_called_class();
84
        if (isset(Benchmark::$start_times[$timer_name])) {
85
            $start_time = Benchmark::$start_times[$timer_name];
86
            unset(Benchmark::$start_times[$timer_name]);
87
        } else {
88
            $start_time = array_pop(Benchmark::$start_times);
89
        }
90
        Benchmark::$times[$timer_name] = number_format(microtime(true) - $start_time, 8);
91
    }
92
93
94
95
    /**
96
     * Measure the memory usage by PHP so far.
97
     *
98
     * @param string  $label      The label to show for this time eg "Start of calling Some_Class::some_function"
99
     * @param boolean $output_now whether to echo now, or wait until EEH_Debug_Tools::show_times() is called
100
     * @return void
101
     */
102
    public static function measureMemory($label, $output_now = false)
103
    {
104
        if (Benchmark::doNotRun()) {
105
            return;
106
        }
107
        $memory_used = Benchmark::convert(memory_get_peak_usage(true));
108
        Benchmark::$memory_usage[$label] = $memory_used;
109
        if ($output_now) {
110
            echo "\r\n<br>$label : $memory_used";
111
        }
112
    }
113
114
115
116
    /**
117
     * will display the benchmarking results at shutdown
118
     *
119
     * @return void
120
     */
121
    public static function displayResultsAtShutdown()
122
    {
123
        add_action(
124
            'shutdown',
125
            function () {
126
                Benchmark::displayResults();
127
            }
128
        );
129
    }
130
131
132
133
    /**
134
     * displayResults
135
     *
136
     * @param bool $echo
137
     * @return string
138
     */
139
    public static function displayResults($echo = true)
140
    {
141
        if (Benchmark::doNotRun()) {
142
            return '';
143
        }
144
        $output = '';
145
        if (! empty(Benchmark::$times)) {
146
            $total = 0;
147
            $output .= '<span style="color:#999999; font-size:.8em;">( time in milliseconds )</span><br />';
148
            foreach (Benchmark::$times as $timer_name => $total_time) {
149
                $output .= Benchmark::formatTime($timer_name, $total_time) . '<br />';
150
                $total += $total_time;
151
            }
152
            $output .= '<br />';
153
            $output .= '<h4>TOTAL TIME</h4>';
154
            $output .= Benchmark::formatTime('', $total);
155
            $output .= '<span style="color:#999999; font-size:.8em;"> milliseconds</span><br />';
156
            $output .= '<br />';
157
            $output .= '<h5>Performance scale (from best to worse)</h5>';
158
            $output .= '<span style="color:mediumpurple">Like wow! How about a Scooby snack?</span><br />';
159
            $output .= '<span style="color:deepskyblue">Like...no way man!</span><br />';
160
            $output .= '<span style="color:limegreen">Like...groovy!</span><br />';
161
            $output .= '<span style="color:gold">Ruh Oh</span><br />';
162
            $output .= '<span style="color:darkorange">Zoinks!</span><br />';
163
            $output .= '<span style="color:red">Like...HEEELLLP</span><br />';
164
        }
165
        if (! empty(Benchmark::$memory_usage)) {
166
            $output .= '<h5>Memory</h5>' . implode('<br />', Benchmark::$memory_usage);
167
        }
168
        if (empty($output)) {
169
            return '';
170
        }
171
        $output = '<div style="border:1px solid #dddddd; background-color:#ffffff;'
172
                  . (is_admin() ? ' margin:2em 2em 2em 180px;' : ' margin:2em;')
173
                  . ' padding:2em;">'
174
                  . '<h4>BENCHMARKING</h4>'
175
                  . $output
176
                  . '</div>';
177
        if ($echo) {
178
            echo $output;
179
            return '';
180
        }
181
        return $output;
182
    }
183
184
185
186
    /**
187
     * Converts a measure of memory bytes into the most logical units (eg kb, mb, etc)
188
     *
189
     * @param int $size
190
     * @return string
191
     */
192
    public static function convert($size)
193
    {
194
        $unit = array('b', 'kb', 'mb', 'gb', 'tb', 'pb');
195
        return round($size / pow(1024, $i = floor(log($size, 1024))), 2) . ' ' . $unit[absint($i)];
196
    }
197
198
199
200
    /**
201
     * @param string $timer_name
202
     * @param float  $total_time
203
     * @return string
204
     */
205
    public static function formatTime($timer_name, $total_time)
206
    {
207
        $total_time *= 1000;
208
        switch ($total_time) {
209
            case $total_time > 12500 :
210
                $color = 'red';
211
                $bold = 'bold';
212
                break;
213
            case $total_time > 2500 :
214
                $color = 'darkorange';
215
                $bold = 'bold';
216
                break;
217
            case $total_time > 500 :
218
                $color = 'gold';
219
                $bold = 'bold';
220
                break;
221
            case $total_time > 100 :
222
                $color = 'limegreen';
223
                $bold = 'normal';
224
                break;
225
            case $total_time > 20 :
226
                $color = 'deepskyblue';
227
                $bold = 'normal';
228
                break;
229
            default :
230
                $color = 'mediumpurple';
231
                $bold = 'normal';
232
                break;
233
        }
234
        return '<span style="min-width: 10px; margin:0 1em; color:'
235
               . $color
236
               . '; font-weight:'
237
               . $bold
238
               . '; font-size:1.2em;">'
239
               . str_pad(number_format($total_time, 3), 9, '0', STR_PAD_LEFT)
240
               . '</span> '
241
               . $timer_name;
242
    }
243
244
245
246
}
247