SDEngine
Game Engine
Loading...
Searching...
No Matches
profiler.hpp
Go to the documentation of this file.
1#pragma once
2#include <cstdio>
3#include <cstdlib>
4#include <cstring>
5#include <string_view>
6#include <x86intrin.h>
7
8#include "core/logging.hpp"
9#include "core/types.hpp"
10
11namespace sd {
12
13namespace detail {
14
15inline U64 get_cpu_mhz() {
16 static U64 cached_mhz = [] {
17 U64 mhz = 0;
18 if (FILE* f = fopen("/proc/cpuinfo", "r")) {
19 char buf[256];
20 while (fgets(buf, sizeof(buf), f)) {
21 if (const char* p = std::strstr(buf, "cpu MHz")) {
22 mhz = static_cast<U64>(std::strtod(p + 7, nullptr));
23 break;
24 }
25 }
26 fclose(f);
27 }
28 return mhz ? mhz : 3000;
29 }();
30 return cached_mhz;
31}
32
33} // namespace detail
34
35struct Profile {
37 const char* name{};
38
39 Profile() = default;
40
41 Profile(const char* name) : name{name} {
42 _mm_lfence();
43 start = __rdtsc();
44 }
45
47 if (!name)
48 return;
49 U32 aux;
50 U64 end = __rdtscp(&aux);
51 _mm_lfence();
52 U64 elapsed = end - start;
54 sd::log::engine::profiler::debug(
55 "{}: {} cycles, {:.2f} ms @ 3GHz, {:.2f} ms @ {} MHz (current)",
56 name,
57 elapsed,
58 elapsed / 3'000'000.0,
59 elapsed / (cur_mhz * 1000.0),
60 cur_mhz);
61 }
62
63 void begin(const char* new_name) {
64 name = new_name;
65 _mm_lfence();
66 start = __rdtsc();
67 }
68
69 U64 end() {
70 U32 aux;
72 _mm_lfence();
75
76 sd::log::engine::profiler::debug(
77 "{}: {} cycles, {:.2f} ms @ 3GHz, {:.2f} ms @ {} MHz (current)",
78 name,
79 elapsed,
80 elapsed / 3'000'000.0,
81 elapsed / (cur_mhz * 1000.0),
82 cur_mhz);
83 name = nullptr;
84 return elapsed;
85 }
86
87 Profile(const Profile&) = delete;
88 Profile& operator=(const Profile&) = delete;
89 Profile(Profile&&) = delete;
91};
92
93inline thread_local Profile _sd_active_profile{};
94} // namespace sd
95
96#define SD_CONCAT_INNER(a, b) a##b
97#define SD_CONCAT(a, b) SD_CONCAT_INNER(a, b)
98
99#define PROFILE(name) \
100 ::sd::Profile SD_CONCAT(_sd_profile_, __LINE__) { \
101 name \
102 }
103#define PROFILE_FUNCTION() PROFILE(__func__)
104
105#define PROFILE_START(name) ::sd::_sd_active_profile.begin(name)
106#define PROFILE_END() ::sd::_sd_active_profile.end()
U64 get_cpu_mhz()
Definition profiler.hpp:15
Definition Application.hpp:22
thread_local Profile _sd_active_profile
Definition profiler.hpp:93
Definition profiler.hpp:35
void begin(const char *new_name)
Definition profiler.hpp:63
Profile(const Profile &)=delete
~Profile() noexcept
Definition profiler.hpp:46
U64 start
Definition profiler.hpp:36
Profile & operator=(Profile &&)=delete
Profile(Profile &&)=delete
const char * name
Definition profiler.hpp:37
Profile & operator=(const Profile &)=delete
U64 end()
Definition profiler.hpp:69
Profile(const char *name)
Definition profiler.hpp:41
Profile()=default
consteval U64 type_id_of()
Definition type_id.hpp:6
std::uint32_t U32
Definition types.hpp:15
std::uint64_t U64
Definition types.hpp:16