summaryrefslogtreecommitdiff
path: root/core/classes/Benchmark.php
blob: 8aa040ddef41cd3b8f55b87dee395ceb8f289d83 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php

/** Benchmarn class
 * -----------------------------------------------------------------------------
 * 
 * Handy class to evaluate the apprication's performace
 * 
 * [*] calulates time difference between any two or more marked timespots;
 * [*] tracks memory usage for the marked timespots
 * [*] creates reports in various formats
 * 
 * TODO: create an (optional) ascii graph ??
 * 
 * -----------------------------------------------------------------------------
 */
class Benchmark {

    /** PROPERTIES
     * -------------------------------------------------------------------------
     */


    /** @var array
     * array of microtimes in [key => val] pairs, where
     * + key (string): is a custom label used for refering
     * + val (float) : the microtime when the timespot was created
     */
    private static $timeSpots = Array();


    /** @var array
     * array of memory used in [key => val] pairs, where
     * + key (string): is a custom label used for refering (same as in $timeSpots)
     * + val (float) : the memory usage (in bytes) when the timespot was created
     */
    private static $memoryUse = Array();


    /** @var boolean
     * flag to determin if reporting is enaabled
     */
    private static $reportEnabled = true;




    /** METHODS
     * -------------------------------------------------------------------------
     */

    
    /** add_timespot
     * ---
     * add new timespot
     * @param $key : label of timespot
     */
    public static function add_spot(string $key)
    {
        self::$timeSpots[$key] = microtime(true);
        self::$memoryUse[$key] = round(memory_get_usage()/(1024*1024),2);
    }


    /** exist
     * checks if a benchmark spot  with label $key exists 
     */
    public static function exist(string $key) : bool
    {
        return isset(self::$timeSpots[$key]);
    }


    /** desableReport
     * (Self-explanatory)
     */
    public static function disableReport()
    {
        self::$reportEnabled = false;
    }


    /** render_benchmark_report
     * ---
     * renders performance report
     * as html comment at the end of webpage in various modes
     * 
     * @param $mode (int): report format id
     * ... default: BENCH_REPORT_COMMENT (5) = report as html comment;
     * ... for more report-formats check the BENCH_REPORT_* defines
     */
    public static function report(string $mode = BENCH_REPORT_COMMENT)
    {
        if ( (self::$reportEnabled) && (!empty(self::$timeSpots)) ) {

            switch ($mode) {
                case BENCH_REPORT_ARRAY:
                    return [
                        'timespots' => self::$timeSpots,
                        'memory_usage' => self::$memoryUse
                    ];
                    break;

                case BENCH_REPORT_JSON:
                    return json_encode([
                        'timespots' => self::$timeSpots,
                        'memory_usage' => self::$memoryUse
                    ], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE);
                    break;

                case BENCH_REPORT_HTML:
                    $open = '<p>';
                    $close = '</b></p>';
                    $divider = ":<b>";
                    $prefix = '<div>';
                    $suffix = '</div>';
                    break;

                case BENCH_REPORT_CODE:
                    $open = '';
                    $close = '';
                    $divider = ": ";
                    $prefix = '<pre>';
                    $suffix = '</pre>';
                    break;

                case BENCH_REPORT_COMMENT:
                default:
                    $open = '<!--';
                    $close = '-->';
                    $divider = ":";
                    $prefix = '';
                    $suffix = '';
                    break;
            }

            $output = $prefix;

            // TIME REPORT 
            // ---------------------------------------------------------------------
            $output .= "\n\n{$open} Timings {$close}";

            // valid from php 7.3
            // $start = self::$timeSpots[ array_key_first(self::$timespots) ];
            // $end = self::$timeSpots[ array_key_last(self::$timespots) ];
            $start = self::$timeSpots['start'];
            $end = self::$timeSpots['end'];
            $all_dt = number_format($end - $start , 4)*1000 ." ms";

            

            // if more than 2 timespots
            // $output .= dt between each spot
            if (count(self::$timeSpots) > 2) {

                // calculate dt between spots
                $time_results = array();
                $prev_key = '';
                $prev_time = 0;
                foreach(self::$timeSpots as $key => $t) {
                    if (!$prev_time) {
                        $prev_time = $t;
                        $prev_key = $key;
                    }
                    else {
                        $dt = number_format($t - $prev_time , 4)*1000 ." ms";
                        $time_results[] = array(
                            'part' => "{$prev_key}[..{$key}]", ///$key,
                            'dt'   => $dt
                        );
                        $prev_key = $key; //// "{$prev_key}[..{$key}]";
                        $prev_time = $t;
                    }
                }

                // $output .= timings
                foreach ($time_results as $key => $val) {
                    $output .= "\n\t{$open} {$val['part']} {$divider} {$val['dt']} {$close}";
                }
            }

            // $output .= total time
            $output .= "\n\t{$open} total {$divider} {$all_dt} {$close}";


            // MEMORY REPORT
            // ---------------------------------------------------------------------
            $output .= "\n\n{$open} Memory Usage {$close}";

            if (count(self::$memoryUse) > 2) {

                foreach (self::$memoryUse as $key => $val) {
                    $output .= "\n\t{$open} {$key} {$divider} {$val}MB {$close}";
                }

            } else {
                $output .= "\n\t{$open} memory usage {$divider} ". round(memory_get_usage()/(1024*1024),2) ."MB {$close}";   
            }

            $output .= $suffix;

        }
        return $output;

    }

}