-
Notifications
You must be signed in to change notification settings - Fork 18
/
prof.h
362 lines (329 loc) · 13 KB
/
prof.h
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
/*
* # Prof
*
* Self-contained C/C++ profiler library for Linux.
*
* Prof offers a quick way to measure performance events (CPU clock cycles,
* cache misses, branch mispredictions, etc.) of C/C++ code snippets. Prof is
* just a wrapper around the `perf_event_open` system call, its main goal is to
* be easy to setup and painless to use for targeted optimizations, namely, when
* the hot spot has already been identified. In no way Prof is a replacement for
* a fully-fledged profiler like perf, gprof, callgrind, etc.
*
* ## Examples
*
* ### Minimal
*
* The following snippet prints the rough number of CPU clock cycles spent in
* executing the code between the two Prof calls:
*
* ```c
* #include "prof.h"
*
* int main()
* {
* PROF_START();
* // slow code goes here...
* PROF_STDOUT();
* }
* ```
*
* ### Custom options
*
* The following snippet instead counts both read and write faults of the level
* 1 data cache that occur in the userland code between the two Prof calls:
*
* ```c
* #include <stdio.h>
*
* #define PROF_USER_EVENTS_ONLY
* #define PROF_EVENT_LIST \
* PROF_EVENT_CACHE(L1D, READ, MISS) \
* PROF_EVENT_CACHE(L1D, WRITE, MISS)
* #include "prof.h"
*
* int main()
* {
* uint64_t faults[2] = { 0 };
*
* PROF_START();
* // slow code goes here...
* PROF_DO(faults[index] += counter);
*
* // fast or uninteresting code goes here...
*
* PROF_START();
* // slow code goes here...
* PROF_DO(faults[index] += counter);
*
* printf("L1: R = %" PRIu64 "; W = %" PRIu64 "\faults[0], faults[1]);
* }
* ```
*
* ## Installation
*
* Just include `prof.h`. Here is a quick way to fetch the latest version:
*
* wget -q https://raw.githubusercontent.com/cyrus-and/prof/master/prof.h
*
* Please be aware that Prof uses `__attribute__((constructor))` to be the more
* straightforward to setup as possible, so the header cannot be included more
* than once.
*
* This also means that in order to use Prof from additional threads, the setup
* code (`prof_init` and `prof_fini` calls) must be replicated for each one of
* them, for example:
*
* ```c
* void *thread(void *args) {
* prof_init();
*
* // ...
*
* prof_fini();
* return NULL;
* }
* ```
*
* ## Setup
*
* Since Prof uses `perf_event_open` make sure to have the permission to access
* the performance counters: either run the program as superuser (discouraged)
* or set the value of `perf_event_paranoid` appropriately, for example:
*
* ```console
* $ echo 1 | sudo tee /proc/sys/kernel/perf_event_paranoid
* ```
*
* Optionally make it permanent with:
*
* ```console
* $ echo 'kernel.perf_event_paranoid=1' | sudo tee /etc/sysctl.d/local.conf
* ```
*
* See `man perf_event_open` for more information.
*/
#ifndef PROF_H
#define PROF_H
#include <errno.h>
#include <inttypes.h>
#include <linux/perf_event.h>
#include <stdarg.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/syscall.h>
#include <unistd.h>
/*
* ## API
*/
/*
* Reset the counters and (re)start counting the events.
*
* The events to be monitored are specified by setting the `PROF_EVENT_LIST`
* macro before including this file to a list of `PROF_EVENT_*` invocations;
* defaults to counting the number CPU clock cycles.
*
* If the `PROF_USER_EVENTS_ONLY` macro is defined before including this file
* then kernel and hypervisor events are excluded from the count.
*/
#define PROF_START() \
do { \
PROF_IOCTL_(ENABLE); \
PROF_IOCTL_(RESET); \
} while (0)
/*
* Specify an event to be monitored, `type` and `config` are defined in the
* documentation of the `perf_event_open` system call.
*/
#define PROF_EVENT(type, config) \
(uint32_t)(type), (uint64_t)(config),
/*
* Same as `PROF_EVENT` but for hardware events; prefix `PERF_COUNT_HW_` must be
* omitted from `config`.
*/
#define PROF_EVENT_HW(config) \
PROF_EVENT(PERF_TYPE_HARDWARE, PERF_COUNT_HW_ ## config)
/*
* Same as `PROF_EVENT` but for software events; prefix `PERF_COUNT_SW_` must be
* omitted from `config`.
*/
#define PROF_EVENT_SW(config) \
PROF_EVENT(PERF_TYPE_SOFTWARE, PERF_COUNT_SW_ ## config)
/*
* Same as `PROF_EVENT` but for cache events; prefixes `PERF_COUNT_HW_CACHE_`,
* `PERF_COUNT_HW_CACHE_OP_` and `PERF_COUNT_HW_CACHE_RESULT_` must be omitted
* from `cache`, `op` and `result`, respectively. Again `cache`, `op` and
* `result` are defined in the documentation of the `perf_event_open` system
* call.
*/
#define PROF_EVENT_CACHE(cache, op, result) \
PROF_EVENT(PERF_TYPE_HW_CACHE, \
(PERF_COUNT_HW_CACHE_ ## cache) | \
(PERF_COUNT_HW_CACHE_OP_ ## op << 8) | \
(PERF_COUNT_HW_CACHE_RESULT_ ## result << 16))
/*
* Stop counting the events. The counter array can then be accessed with
* `PROF_COUNTERS`.
*/
#define PROF_STOP() \
do { \
PROF_IOCTL_(DISABLE); \
PROF_READ_COUNTERS_(prof_event_buf_); \
} while (0)
/*
* Access the counter array. The order of counters is the same of the events
* defined in `PROF_EVENT_LIST`. Elements of this array are 64 bit unsigned
* integers.
*/
#define PROF_COUNTERS \
(prof_event_buf_ + 1)
/*
* Stop counting the events and execute the code provided by `block` for each
* event. Within `code`: `index` refers to the event position index in the
* counter array defined by `PROF_COUNTERS`; `counter` is the actual value of
* the counter. `index` is a 64 bit unsigned integer.
*/
#define PROF_DO(block) \
do { \
uint64_t i_; \
PROF_STOP(); \
for (i_ = 0; i_ < prof_event_cnt_; i_++) { \
uint64_t index = i_; \
uint64_t counter = prof_event_buf_[i_ + 1]; \
(void)index; \
(void)counter; \
block; \
} \
} while (0)
/*
* Same as `PROF_DO` except that `callback` is the name of a *callable* object
* (e.g. a function) which, for each event, is be called with the two parameters
* `index` and `counter`.
*/
#define PROF_CALL(callback) \
PROF_DO(callback(index, counter))
/*
* Stop counting the events and write to `file` (a stdio.h `FILE *`) as many
* lines as are events in `PROF_EVENT_LIST`. Each line contains `index` and
* `counter` (as defined by `PROF_DO`) separated by a tabulation character. If
* there is only one event then `index` is omitted.
*/
#define PROF_FILE(file) \
PROF_DO(if (prof_event_cnt_ > 1) { \
fprintf((file), "%" PRIu64 "\t%" PRIu64 "\n", index, counter); \
} else { \
fprintf((file), "%" PRIu64 "\n", counter); \
} \
)
/*
* Same as `PROF_LOG_FILE` except that `file` is `stdout`.
*/
#define PROF_STDOUT() \
PROF_FILE(stdout)
/*
* Same as `PROF_LOG_FILE` except that `file` is `stderr`.
*/
#define PROF_STDERR() \
PROF_FILE(stderr)
/* DEFAULTS ----------------------------------------------------------------- */
#ifndef PROF_EVENT_LIST
#ifdef PERF_COUNT_HW_REF_CPU_CYCLES /* since Linux 3.3 */
#define PROF_EVENT_LIST PROF_EVENT_HW(REF_CPU_CYCLES)
#else
#define PROF_EVENT_LIST PROF_EVENT_HW(CPU_CYCLES)
#endif
#endif
/* UTILITY ------------------------------------------------------------------ */
#define PROF_ASSERT_(x) \
do { \
if (!(x)) { \
fprintf(stderr, "# %s:%d: PROF error", __FILE__, __LINE__); \
if (errno) { \
fprintf(stderr, " (%s)", strerror(errno)); \
} \
printf("\n"); \
abort(); \
} \
} while (0)
#define PROF_IOCTL_(mode) \
do { \
PROF_ASSERT_(ioctl(prof_fd_, \
PERF_EVENT_IOC_ ## mode, \
PERF_IOC_FLAG_GROUP) != -1); \
} while (0)
#define PROF_READ_COUNTERS_(buffer) \
do { \
const ssize_t to_read = sizeof(uint64_t) * (prof_event_cnt_ + 1); \
PROF_ASSERT_(read(prof_fd_, buffer, to_read) == to_read); \
} while (0)
/* SETUP -------------------------------------------------------------------- */
static __thread int prof_fd_;
static __thread uint64_t prof_event_cnt_;
static __thread uint64_t *prof_event_buf_;
static void prof_init_(uint64_t dummy, ...) {
uint32_t type;
va_list ap;
prof_fd_ = -1;
prof_event_cnt_ = 0;
va_start(ap, dummy);
while (type = va_arg(ap, uint32_t), type != (uint32_t)-1) {
struct perf_event_attr pe;
uint64_t config;
int fd;
config = va_arg(ap, uint64_t);
memset(&pe, 0, sizeof(struct perf_event_attr));
pe.size = sizeof(struct perf_event_attr);
pe.read_format = PERF_FORMAT_GROUP;
pe.type = type;
pe.config = config;
#ifdef PROF_USER_EVENTS_ONLY
pe.exclude_kernel = 1;
pe.exclude_hv = 1;
#endif
fd = syscall(__NR_perf_event_open, &pe, 0, -1, prof_fd_, 0);
PROF_ASSERT_(fd != -1);
if (prof_fd_ == -1) {
prof_fd_ = fd;
}
prof_event_cnt_++;
}
va_end(ap);
prof_event_buf_ = (uint64_t *)malloc((prof_event_cnt_ + 1) *
sizeof(uint64_t));
}
void __attribute__((constructor)) prof_init()
{
prof_init_(0, PROF_EVENT_LIST /*,*/ (uint32_t)-1);
}
void __attribute__((destructor)) prof_fini()
{
PROF_ASSERT_(close(prof_fd_) != -1);
free(prof_event_buf_);
}
#endif
/*
* ## License
*
* Copyright (c) 2024 Andrea Cardaci <cyrus.and@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/