Refactor profiling code

This commit is contained in:
2023-07-09 00:55:22 +01:00
parent 2e9c2dc6d5
commit 0073114723
3 changed files with 162 additions and 109 deletions

View File

@@ -1,9 +1,29 @@
#include "profiler/timer.h"
#include "aliases.h"
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <x86intrin.h>
#define MAX_PROFILE_SAMPLES 1024
typedef struct {
const char *title;
u64 duration;
} profiler_sample_t;
typedef struct {
profiler_sample_t samples[MAX_PROFILE_SAMPLES];
u64 cpu_freq;
u64 size;
u64 start;
u64 end;
u64 max_title_length;
} profiler_t;
INTERNAL profiler_t profiler = {0};
typedef struct timespec timespec_t;
u64 get_os_frequency() { return 1000000000; }
@@ -44,3 +64,63 @@ u64 get_cpu_freq(u64 milliseconds) {
return cpu_freq;
}
void profile_start() {
profiler.cpu_freq = get_cpu_freq(500);
profiler.start = read_cpu_timer();
profiler.max_title_length = 0;
}
void profile_end() {
if (!profiler.start || !profiler.size) {
return;
}
profiler.end = read_cpu_timer();
u64 total = profiler.end - profiler.start;
u16 time_precision = 16;
u16 time_char_count = 20;
u16 duration_char_count = 22;
u16 percentage_precision = 8;
u16 percentage_char_count = 12;
// clang-format off
printf("\n==============================PROFILING==============================\n");
// clang-format on
if (profiler.cpu_freq) {
printf("Total: %*.*f seconds (CPU frequency: %llu hz/sec)\n\n",
time_char_count, time_precision, (f64)total / profiler.cpu_freq,
(unsigned long long)profiler.cpu_freq);
}
profiler_sample_t *sample = NULL;
for (u64 i = 0; i < profiler.size; ++i) {
sample = &(profiler.samples[i]);
printf("%*s: %*lld (%*.*f %%)\n", (i32)profiler.max_title_length,
sample->title, duration_char_count,
(unsigned long long)sample->duration, percentage_char_count,
percentage_precision, (f64)sample->duration / total * 100.0);
}
}
void add_sample(const char *title, u64 duration) {
if (profiler.size == MAX_PROFILE_SAMPLES) {
return;
}
u64 length = strlen(title);
if (length > profiler.max_title_length) {
profiler.max_title_length = length;
}
profiler.samples[(profiler.size)++] = (profiler_sample_t){
.title = title,
.duration = duration,
};
}