-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcranberry_profiler.h
620 lines (494 loc) · 15.1 KB
/
cranberry_profiler.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
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
#ifndef __CRANBERRY_PROFILER_H
#define __CRANBERRY_PROFILER_H
/*
cran_profiler Usage, License: MIT
About:
The cran_profiler is a single header utility that generates chrome:\\tracing json that can be then imported and viewed using chrome's
tracing utility. cran_profiler is completely thread safe and attempts to minimize contention between thread.
Usage:
Using cran_profiler is simple,
SETUP/TEARDOWN:
- #define CRANPR_IMPLEMENTATION before including the header file in one of your source files.
- #define CRANPR_ENABLE to enable profiling
- cranpr_init(); to init
- cranpr_terminate(); to close
NOTE: Chrome://tracing matches these calls by name and category assuring a unique name is important.
WARNING: Category and Name are not stored, their lifetime must exist either until program termination or until the next call to cranpr_flush_thread_buffer and cranpr_flush.
USAGE:
Once a significant amount of samples have been gathered, samples have to be flushed.
A simple way to do this is shown below
{
// Buffers are only added to the list once they are full. This minimizes contention and allows simple modification of the buffers.
// The buffers are also stored as thread local globals, and thus must be flushed from their respective threads.
if(cranpr_captured_size() == 0)
{
// Adds the current buffer to the list of buffers even if it hasn't been filled up yet.
cranpr_flush_thread_buffer();
}
char* print;
size_t bufferSize;
cranpr_flush_alloc(&print, &bufferSize);
fprintf(fileHandle, "%s", cranpr_profile_preface);
fprintf(fileHandle, "%s", print);
fprintf(fileHandle, "%s", cranpr_profile_postface);
free(print);
}
THREADING:
It is important to call cranpr_flush_thread_buffer() before shutting down a thread and
before the last flush as the remaining buffers might have some samples left in them.
A multithreaded program could have the format:
{
Init Profiler
Add cranpr_profile_preface to the file
Startup job threads
Create samples in these threads
At thread termination, call cranpr_flush_thread_buffer()
Startup flushing thread
Call cranpr_captured_size()
If there are buffers, flush them to a file
At thread termination, call cranpr_flush_thread_buffer()
Kill all the threads
Call cranpr_flush_alloc() to flush the remaining buffers
Print to a file
Add cranpr_profile_postface to the file
Terminate the profiler
}
*/
/* -API- */
#include <stdint.h>
#define cranpr_type_begin 'B'
#define cranpr_type_end 'E'
#define cranpr_type_instance 'I'
#ifdef CRANPR_ENABLED
#define cranpr_begin(cat, name) cranpr_write_sample(cranpr_create_sample(cat, name, cranpr_timestamp(), cranpr_type_begin));
#define cranpr_end(cat, name) cranpr_write_sample(cranpr_create_sample(cat, name, cranpr_timestamp(), cranpr_type_end));
#define cranpr_event(cat, name) cranpr_write_sample(cranpr_create_sample(cat, name, cranpr_timestamp(), cranpr_type_instance));
#else
#define cranpr_begin(cat, name)
#define cranpr_end(cat, name)
#define cranpr_event(cat, name)
#endif
typedef struct
{
int64_t timeStamp;
const char* category;
const char* name;
uint16_t processorID;
uint16_t threadID;
char eventType;
} cranpr_sample_t;
static const char* cranpr_profile_preface = "{\"traceEvents\":[";
static const char* cranpr_profile_postface = "]}";
void cranpr_init(void);
void cranpr_terminate(void);
cranpr_sample_t cranpr_create_sample(const char* category, const char* name, int64_t timeStamp, char eventType);
void cranpr_write_sample(cranpr_sample_t sample);
uint16_t cranpr_captured_size();
size_t cranpr_string_size(void);
/* returns the written size */
size_t cranpr_flush(char* buffer, size_t* maxBufferSize);
/* returns the written size*/
size_t cranpr_flush_alloc(char** buffer, size_t* bufferSize);
void cranpr_free(char* buffer);
void cranpr_flush_thread_buffer(void);
int64_t cranpr_timestamp(void);
void cranpr_write_to_file(const char* filePath);
#endif /* __CRANBERRY_PROFILER_H */
/* -Implementation- */
#ifdef CRANPR_IMPLEMENTATION
/* -Platform Macros- */
#if defined(_WIN32) || defined(_WIN64) || defined(__WIN32__)
#define CRANPR_WIN 1
#elif defined(macintosh) || defined(Macintosh) || defined(__APPLE__) && defined(__MACH__)
#define CRANPR_MAC 1
#elif defined(__unix__) || defined(__unix)
#define CRANPR_UNIX 1
#else
#error "cranpr unsupported platform!"
#endif
#if defined(_MSC_VER)
#define CRANPR_MSVC 1
#elif defined(__GNUC__)
#define CRANPR_GCC 1
#else
#error "cranpr unsupported compiler!"
#endif
#include <assert.h>
#include <string.h>
#include <stdbool.h>
#include <inttypes.h>
#include <stdio.h>
#include <math.h>
#if CRANPR_WIN
#include <Windows.h>
#endif
#define cranpr_unused(a) (void)a
/* -Threads- */
#if CRANPR_MSVC
#define CRANPR_THREAD_LOCAL __declspec( thread )
#else
#error "cranpr thread local storage not implemented!"
#endif
#if CRANPR_WIN
typedef CRITICAL_SECTION cranpr_lock_t;
#else
#error "cranpr Mutex not implemented!"
#endif
void cranpr_init_lock(cranpr_lock_t* lock)
{
#if CRANPR_WIN
InitializeCriticalSection(lock);
#else
#error "cranpr_init_lock not implemented!"
#endif
}
void cranpr_terminate_lock(cranpr_lock_t* lock)
{
#if CRANPR_WIN
DeleteCriticalSection(lock);
#else
#error cranpr_terminate_lock not implemented!"
#endif
}
void cranpr_lock_section(cranpr_lock_t* lock)
{
#if CRANPR_WIN
EnterCriticalSection(lock);
#else
#error "cranpr_lock_section not implemented!"
#endif
}
void cranpr_unlock_section(cranpr_lock_t* lock)
{
#if CRANPR_WIN
LeaveCriticalSection(lock);
#else
#error "cranpr_unlock_section not implemented!"
#endif
}
uint16_t cranpr_get_thread_id( void )
{
#if CRANPR_WIN
return (uint16_t)GetCurrentThreadId();
#else
#error "cranpr_get_thread_id not implemented!"
#endif
}
uint16_t cranpr_get_process_id( void )
{
#if CRANPR_WIN
return (uint16_t)GetProcessId(GetCurrentProcess());
#else
#error "cranpr_get_process_id not implemented!"
#endif
}
/* -Timer- */
int64_t cranpr_timestamp( void )
{
#if CRANPR_WIN
LARGE_INTEGER frequency;
BOOL queryResult = FALSE;
cranpr_unused(queryResult);
queryResult = QueryPerformanceFrequency(&frequency);
assert(queryResult == TRUE);
LARGE_INTEGER time;
queryResult = QueryPerformanceCounter(&time);
assert(queryResult == TRUE);
int64_t microSeconds = (int64_t)time.QuadPart * 1000000;
return microSeconds / (int64_t)frequency.QuadPart;
#else
#error "cranpr_timestamp not implemented!"
#endif
}
/* -Profiler- */
cranpr_sample_t cranpr_create_sample(const char* category, const char* name, int64_t timeStamp, char eventType)
{
cranpr_sample_t sample;
sample.timeStamp = timeStamp;
sample.category = category;
sample.name = name;
sample.processorID = cranpr_get_process_id();
sample.threadID = cranpr_get_thread_id();
sample.eventType = eventType;
return sample;
}
/* Bigger buffers mean less contention for the list, but also means longer flushes and more memory usage */
#define cranpr_buffer_size 1024
typedef struct
{
cranpr_sample_t samples[cranpr_buffer_size];
uint16_t nextSampleWrite;
} cranpr_buffer_t;
typedef struct
{
cranpr_buffer_t buffer;
void* next;
} cranpr_buffer_node_t;
typedef struct
{
cranpr_buffer_node_t* first;
cranpr_buffer_node_t* last;
uint16_t listSize;
cranpr_lock_t lock;
} cranpr_buffer_list_t;
cranpr_buffer_list_t cranpr_buffer_list;
CRANPR_THREAD_LOCAL cranpr_buffer_t cranpr_buffer;
void cranpr_init( void )
{
cranpr_init_lock(&cranpr_buffer_list.lock);
}
/* Terminate musst be the last thing called, assure that profiling events will no longer be called once this is called */
void cranpr_terminate( void )
{
cranpr_buffer_node_t* iter;
cranpr_lock_section(&cranpr_buffer_list.lock);
iter = cranpr_buffer_list.first;
cranpr_buffer_list.first = NULL;
cranpr_buffer_list.last = NULL;
cranpr_buffer_list.listSize = 0;
cranpr_unlock_section(&cranpr_buffer_list.lock);
cranpr_terminate_lock(&cranpr_buffer_list.lock);
while (iter != NULL)
{
cranpr_buffer_node_t* next = (cranpr_buffer_node_t*)iter->next;
free(iter);
iter = next;
}
}
uint16_t cranpr_captured_size()
{
return cranpr_buffer_list.listSize;
}
/* Not thread safe */
static void cranpr_add_buffer(cranpr_buffer_t* buffer)
{
cranpr_buffer_node_t* node = (cranpr_buffer_node_t*)malloc(sizeof(cranpr_buffer_node_t));
memcpy(&node->buffer, buffer, sizeof(cranpr_buffer_t));
node->next = NULL;
if (cranpr_buffer_list.first == NULL)
{
assert(cranpr_buffer_list.last == NULL);
cranpr_buffer_list.first = node;
cranpr_buffer_list.last = node;
cranpr_buffer_list.listSize = 1;
}
else
{
assert(cranpr_buffer_list.listSize != UINT16_MAX);
assert(cranpr_buffer_list.last->next == NULL);
cranpr_buffer_list.last->next = node;
cranpr_buffer_list.last = node;
cranpr_buffer_list.listSize++;
}
}
/* Format: process Id, thread Id, timestamp, event, category, name */
static const char* const cranpr_sample = "{\"pid\":%" PRIu16 ", \"tid\":%" PRIu16 ", \"ts\":%" PRId64 ", \"ph\":\"%c\", \"cat\": \"%s\", \"name\": \"%s\", \"args\":{\"t\":\"hi\"}},";
static size_t cranpr_sample_size(cranpr_sample_t* sample)
{
size_t sampleSize = sizeof("{\"pid\":") - 1;
sampleSize += sample->processorID == 0 ? 1 : (size_t)log10f((float)sample->processorID);
sampleSize += sizeof(",\"tid\":") - 1;
sampleSize += sample->threadID == 0 ? 1 : (size_t)log10f((float)sample->threadID);
sampleSize += sizeof(",\"ts\":") - 1;
sampleSize += sample->timeStamp == 0 ? 1 : (size_t)log10((double)sample->timeStamp);
sampleSize += sizeof(",\"ph\":\"") - 1;
sampleSize += 1; /* sample char */
sampleSize += sizeof("\",\"cat\":\"") - 1;
sampleSize += strlen(sample->category);
sampleSize += sizeof("\", \"name\": \"") - 1;
sampleSize += strlen(sample->name);
sampleSize += sizeof("\", \"args\":{\"t\":\"hi\"}}") - 1;
return sampleSize;
}
static void cranpr_reverse(char* start, char* end)
{
end -= 1;
for (; start < end; start++, end--)
{
char t = *start;
*start = *end;
*end = t;
}
}
static void cranpr_write_u16(uint16_t val, char* writeBuffer, size_t* writePos)
{
size_t start = *writePos;
while (val >= 10)
{
// Avoid modulo for debug builds
uint16_t t = val / 10;
writeBuffer[(*writePos)++] = '0' + (char)(val - t * 10);
val = t;
}
writeBuffer[(*writePos)++] = '0' + (char)val;
cranpr_reverse(writeBuffer + start, writeBuffer + *writePos);
}
static void cranpr_write_i64(int64_t val, char* writeBuffer, size_t* writePos)
{
size_t start = *writePos;
while (val >= 10)
{
// Avoid modulo for debug builds
int64_t t = val / 10;
writeBuffer[(*writePos)++] = '0' + (char)(val - t * 10);
val = t;
}
writeBuffer[(*writePos)++] = '0' + (char)val;
cranpr_reverse(writeBuffer + start, writeBuffer + *writePos);
}
#define cranpr_memcpy_const_str(str, writeBuffer, writePos) \
{ \
memcpy(writeBuffer + *writePos, str, sizeof(str) - 1); \
*writePos += sizeof(str) - 1; \
}
static void cranpr_write_sample_to_string(cranpr_sample_t* sample, char* writeBuffer, size_t* writePos)
{
cranpr_memcpy_const_str("{\"pid\":", writeBuffer, writePos);
cranpr_write_u16(sample->processorID, writeBuffer, writePos);
cranpr_memcpy_const_str(",\"tid\":", writeBuffer, writePos);
cranpr_write_u16(sample->threadID, writeBuffer, writePos);
cranpr_memcpy_const_str(",\"ts\":", writeBuffer, writePos);
cranpr_write_i64(sample->timeStamp, writeBuffer, writePos);
cranpr_memcpy_const_str(",\"ph\":\"", writeBuffer, writePos);
writeBuffer[(*writePos)++] = sample->eventType;
cranpr_memcpy_const_str("\",\"cat\":\"", writeBuffer, writePos);
size_t strSize = strlen(sample->category);
memcpy(writeBuffer + (*writePos), sample->category, strSize);
(*writePos) += strSize;
cranpr_memcpy_const_str("\",\"name\":\"", writeBuffer, writePos);
strSize = strlen(sample->name);
memcpy(writeBuffer + (*writePos), sample->name, strSize);
(*writePos) += strSize;
cranpr_memcpy_const_str("\",\"args\":{\"t\":\"hi\"}}", writeBuffer, writePos);
}
/* Calculates the size of the samples, allowing the memory to be allocated in one chunk */
/* Thread safe */
size_t cranpr_string_size(void)
{
cranpr_buffer_node_t* start;
/* We have to keep the lock while calculating the string size. We don't want the list to be stolen or modified while we're working. */
cranpr_lock_section(&cranpr_buffer_list.lock);
start = cranpr_buffer_list.first;
size_t size = 0;
while (start != NULL)
{
cranpr_buffer_node_t* next = (cranpr_buffer_node_t*)start->next;
for (uint16_t i = 0; i < start->buffer.nextSampleWrite; i++)
{
cranpr_sample_t* sample = &start->buffer.samples[i];
size += cranpr_sample_size(sample);
size += (next != NULL || (i < start->buffer.nextSampleWrite - 1)) ? 1 : 0;
}
start = next;
}
cranpr_unlock_section(&cranpr_buffer_list.lock);
return size + 1;
}
/* Returns a string to be printed, this takes time. */
/* Thread safe */
/* bufferSize must be at least >= cranpr_string_size(...) */
size_t cranpr_flush( char* buffer, size_t* bufferSize )
{
assert(bufferSize != NULL);
if (*bufferSize < 4)
{
assert(*bufferSize == 1);
buffer[0] = '\0';
return 1;
}
cranpr_buffer_node_t* start;
cranpr_lock_section(&cranpr_buffer_list.lock);
start = cranpr_buffer_list.first;
cranpr_buffer_list.first = NULL;
cranpr_buffer_list.last = NULL;
cranpr_buffer_list.listSize = 0;
cranpr_unlock_section(&cranpr_buffer_list.lock);
if (start == NULL)
{
buffer[0] = '\0';
return 1;
}
size_t size = 0;
while (start != NULL)
{
cranpr_buffer_node_t* next = (cranpr_buffer_node_t*)start->next;
for (uint16_t i = 0; i < start->buffer.nextSampleWrite; i++)
{
cranpr_sample_t* sample = &start->buffer.samples[i];
cranpr_write_sample_to_string(sample, buffer, &size);
if (next != NULL || (i < start->buffer.nextSampleWrite - 1))
{
buffer[size++] = ',';
}
}
free(start);
start = next;
}
if (size >= *bufferSize)
{
assert(false);
return 0;
}
buffer[size] = '\0';
return size + 1;
}
size_t cranpr_flush_alloc(char** buffer, size_t* bufferSize)
{
*bufferSize = cranpr_string_size();
*buffer = (char*)malloc(*bufferSize);
return cranpr_flush(*buffer, bufferSize);
}
void cranpr_free(char* buffer)
{
free(buffer);
}
/* Thread safe */
void cranpr_write_sample(cranpr_sample_t sample)
{
cranpr_buffer.samples[cranpr_buffer.nextSampleWrite] = sample;
cranpr_buffer.nextSampleWrite++;
if (cranpr_buffer.nextSampleWrite == cranpr_buffer_size)
{
cranpr_lock_section(&cranpr_buffer_list.lock);
cranpr_add_buffer(&cranpr_buffer);
cranpr_buffer.nextSampleWrite = 0;
cranpr_unlock_section(&cranpr_buffer_list.lock);
}
}
/* Thread safe */
void cranpr_flush_thread_buffer( void )
{
cranpr_lock_section(&cranpr_buffer_list.lock);
cranpr_add_buffer(&cranpr_buffer);
cranpr_buffer.nextSampleWrite = 0;
cranpr_unlock_section(&cranpr_buffer_list.lock);
}
void cranpr_write_to_file(const char* filePath)
{
#ifdef WIN32
FILE* fileHandle;
errno_t error = fopen_s(&fileHandle, filePath, "w");
if (error != 0)
{
return;
}
#else
FILE* fileHandle = fopen(filePath, "w");
if (fileHandle == NULL)
{
return;
}
#endif // WIN32
char* print = 0;
size_t bufferSize = 0;
size_t writtenSize = cranpr_flush_alloc(&print, &bufferSize);
if (writtenSize > 0)
{
fprintf(fileHandle, "%s", cranpr_profile_preface);
fprintf(fileHandle, "%s", print);
fprintf(fileHandle, "%s", cranpr_profile_postface);
}
cranpr_free(print);
fclose(fileHandle);
}
#endif /* CRANPR_IMPLEMENTATION */