summaryrefslogtreecommitdiffstats
path: root/source/base/base_profile_x64.cpp
blob: d510ce059630f330a538b7f6662696179a4a9df2 (plain) (blame)
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
#if COMPILER_MSVC
#include <intrin.h>
#else
#include <x86intrin.h>
#endif

internal inline u64 ReadCPUTimer(void)
{
	return (u64)__rdtsc();
}

internal u64 base_os_monotonic_ns(void)
{
#if PLATFORM_WINDOWS
	LARGE_INTEGER counter, frequency;
	QueryPerformanceCounter(&counter);
	QueryPerformanceFrequency(&frequency);
	return (u64)((f64)counter.QuadPart * 1e9 / (f64)frequency.QuadPart);
#else
	struct timespec now;
	clock_gettime(CLOCK_MONOTONIC, &now);
	return (u64)now.tv_sec * 1000000000ull + (u64)now.tv_nsec;
#endif
}

internal u64 ReadCPUTimerFreq(void)
{
	// NOTE: count ticks over ~10ms of wall clock, once
	local_persist u64 frequency = 0;
	if(!frequency) {
		u64 start_ns = base_os_monotonic_ns();
		u64 start    = ReadCPUTimer();
		while(base_os_monotonic_ns() - start_ns < 10000000ull) {}
		u64 elapsed_ns = base_os_monotonic_ns() - start_ns;
		frequency      = (u64)((f64)(ReadCPUTimer() - start) * 1e9 / (f64)elapsed_ns);
	}
	return frequency;
}