summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Application/Benchmark.php
blob: 32a05ec9825feffc3ab159b9657f8fb5ab120774 (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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
<?php
/* Icinga Web 2 | (c) 2013 Icinga Development Team | GPLv2+ */

/**
 * Icinga\Application\Benchmark class
 */
namespace Icinga\Application;

use Icinga\Util\Format;

/**
 * This class provides a simple and lightweight benchmark class
 *
 * <code>
 * Benchmark::measure('Program started');
 * // ...do something...
 * Benchmark::measure('Task finieshed');
 * Benchmark::dump();
 * </code>
 */
class Benchmark
{
    const TIME   = 0x01;
    const MEMORY = 0x02;

    protected static $instance;
    protected $start;
    protected $measures = array();

    /**
     * Add a measurement to your benchmark
     *
     * The same identifier can also be used multiple times
     *
     * @param  string  A comment identifying the current measurement
     * @return void
     */
    public static function measure($message)
    {
        self::getInstance()->measures[] = (object) array(
            'timestamp'   => microtime(true),
            'memory_real' => memory_get_usage(true),
            'memory'      => memory_get_usage(),
            'message'     => $message
        );
    }

    /**
     * Throws all measurements away
     *
     * This empties your measurement table and allows you to restart your
     * benchmark from scratch
     *
     * @return void
     */
    public static function reset()
    {
        self::$instance = null;
    }

    /**
     * Rerieve benchmark start time
     *
     * This will give you the timestamp of your first measurement
     *
     * @return float
     */
    public static function getStartTime()
    {
        return self::getInstance()->start;
    }

    /**
     * Dump benchmark data
     *
     * Will dump a text table if running on CLI and a simple HTML table
     * otherwise. Use Benchmark::TIME and Benchmark::MEMORY to choose whether
     * you prefer to show either time or memory or both in your output
     *
     * @param  ?int $what  Whether to get time and/or memory summary
     */
    public static function dump($what = null)
    {
        if (Icinga::app()->isCli()) {
            echo self::renderToText($what);
        } else {
            echo self::renderToHtml($what);
        }
    }

    /**
     * Render benchmark data to a simple text table
     *
     * Use Benchmark::TIME and Icinga::MEMORY to choose whether you prefer to
     * show either time or memory or both in your output
     *
     * @param  ?int $what   Whether to get time and/or memory summary
     * @return string
     */
    public static function renderToText($what = null)
    {
        $data = self::prepareDataForRendering($what);
        $sep = '+';
        $title = '|';
        foreach ($data->columns as & $col) {
            $col->format = ' %'
                   . ($col->align === 'right' ? '' : '-')
                   . $col->maxlen . 's |';

            $sep   .= str_repeat('-', $col->maxlen) . '--+';
            $title .= sprintf($col->format, $col->title);
        }

        $out = $sep . "\n" . $title . "\n" . $sep . "\n";
        foreach ($data->rows as & $row) {
            $r = '|';
            foreach ($data->columns as $key => & $col) {
                $r .= sprintf($col->format, $row[$key]);
            }
            $out .= $r . "\n";
        }

        $out .= $sep . "\n";
        return $out;
    }

    /**
     * Render benchmark data to a simple HTML table
     *
     * Use Benchmark::TIME and Benchmark::MEMORY to choose whether you prefer
     * to show either time or memory or both in your output
     *
     * @param  ?int $what  Whether to get time and/or memory summary
     *
     * @return string
     */
    public static function renderToHtml($what = null)
    {
        $data = self::prepareDataForRendering($what);

        // TODO: Move formatting to CSS file
        $html = '<table class="benchmark">' . "\n" . '<tr>';
        foreach ($data->columns as & $col) {
            if ($col->title === 'Time') {
                continue;
            }
            $html .= sprintf(
                '<td align="%s">%s</td>',
                $col->align,
                htmlspecialchars($col->title)
            );
        }
        $html .= "</tr>\n";

        foreach ($data->rows as & $row) {
            $html .= '<tr>';
            foreach ($data->columns as $key => & $col) {
                if ($col->title === 'Time') {
                    continue;
                }
                $html .= sprintf(
                    '<td align="%s">%s</td>',
                    $col->align,
                    $row[$key]
                );
            }
            $html .= "</tr>\n";
        }
        $html .= "</table>\n";
        return $html;
    }

    /**
     * Prepares benchmark data for output
     *
     * Use Benchmark::TIME and Benchmark::MEMORY to choose whether you prefer
     * to have either time or memory or both in your output
     *
     * @param  ?int $what  Whether to get time and/or memory summary
     *
     * @return object
     */
    protected static function prepareDataForRendering($what = null)
    {
        if ($what === null) {
            $what = self::TIME | self::MEMORY;
        }

        $columns = array(
            (object) array(
                'title'  => 'Time',
                'align'  => 'left',
                'maxlen' => 4
            ),
            (object) array(
                'title'  => 'Description',
                'align'  => 'left',
                'maxlen' => 11
            )
        );
        if ($what & self::TIME) {
            $columns[] = (object) array(
                'title'  => 'Off (ms)',
                'align'  => 'right',
                'maxlen' => 11
            );
            $columns[] = (object) array(
                'title'  => 'Dur (ms)',
                'align'  => 'right',
                'maxlen' => 13
            );
        }
        if ($what & self::MEMORY) {
            $columns[] = (object) array(
                'title'  => 'Mem (diff)',
                'align'  => 'right',
                'maxlen' => 10
            );
            $columns[] = (object) array(
                'title'  => 'Mem (total)',
                'align'  => 'right',
                'maxlen' => 11
            );
        }

        $bench = self::getInstance();
        $last = $bench->start;
        $rows = array();
        $lastmem = 0;
        foreach ($bench->measures as $m) {
            $micro = sprintf(
                '%03d',
                round(($m->timestamp - floor($m->timestamp)) * 1000)
            );
            $vals = array(
                date('H:i:s', (int) $m->timestamp) . '.' . $micro,
                $m->message
            );

            if ($what & self::TIME) {
                $m->relative = $m->timestamp - $bench->start;
                $m->offset   = $m->timestamp - $last;
                $last = $m->timestamp;
                $vals[] = sprintf('%0.3f', $m->relative * 1000);
                $vals[] = sprintf('%0.3f', $m->offset * 1000);
            }

            if ($what & self::MEMORY) {
                $mem = $m->memory - $lastmem;
                $lastmem = $m->memory;
                $vals[] = Format::bytes($mem);
                $vals[] = Format::bytes($m->memory);
            }

            $row = & $rows[];
            foreach ($vals as $col => $val) {
                $row[$col] = $val;
                $columns[$col]->maxlen = max(
                    strlen($val),
                    $columns[$col]->maxlen
                );
            }
        }

        return (object) array(
            'columns' => $columns,
            'rows' => $rows
        );
    }

    /**
     * Singleton
     *
     * Benchmark is run only once, but you are not allowed to directly access
     * the getInstance() method
     *
     * @return self
     */
    protected static function getInstance()
    {
        if (self::$instance === null) {
            self::$instance = new Benchmark();
            self::$instance->start = microtime(true);
        }

        return self::$instance;
    }

    /**
     * Constructor
     *
     * Singleton usage is enforced, the only way to instantiate Benchmark is by
     * starting your measurements
     *
     * @return void
     */
    protected function __construct()
    {
    }
}