aboutsummaryrefslogtreecommitdiff
path: root/zencore/timer.cpp
blob: f67822e73b8bcfcd2ae92d55dee7475f8a33b11f (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
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
// Copyright Epic Games, Inc. All Rights Reserved.

#include <doctest/doctest.h>
#include <zencore/thread.h>
#include <zencore/timer.h>
#if ZEN_PLATFORM_WINDOWS
#	include <zencore/windows.h>
#elif ZEN_PLATFORM_LINUX
#	include <time.h>
#	include <unistd.h>
#endif

namespace zen {

uint64_t
GetHifreqTimerValue()
{
#if ZEN_PLATFORM_WINDOWS
	LARGE_INTEGER li;
	QueryPerformanceCounter(&li);

	return li.QuadPart;
#else
	struct timespec ts;
	clock_gettime(CLOCK_MONOTONIC, &ts);
	return (uint64_t(ts.tv_sec) * 1000000ull) + (uint64_t(ts.tv_nsec) / 1000ull);
#endif
}

uint64_t
internalGetHifreqTimerFrequency()
{
#if ZEN_PLATFORM_WINDOWS
	LARGE_INTEGER li;
	QueryPerformanceFrequency(&li);

	return li.QuadPart;
#else
	return 1000000ull;
#endif
}

static uint64_t qpcFreq = internalGetHifreqTimerFrequency();

uint64_t
GetHifreqTimerFrequency()
{
	return qpcFreq;
}

uint64_t
GetHifreqTimerFrequencySafe()
{
	if (!qpcFreq)
		qpcFreq = internalGetHifreqTimerFrequency();

	return qpcFreq;
}

//////////////////////////////////////////////////////////////////////////

#if !ZEN_PLATFORM_WINDOWS
void Sleep(uint32_t ms)
{
	usleep(ms * 1000U);
}
#endif

//////////////////////////////////////////////////////////////////////////
//
// Testing related code follows...
//

void
timer_forcelink()
{
}

TEST_CASE("Timer")
{
	uint64_t s0 = GetHifreqTimerValue();
	uint64_t t0 = GetCpuTimerValue();
	Sleep(1000);
	uint64_t s1 = GetHifreqTimerValue();
	uint64_t t1 = GetCpuTimerValue();
	// double r = double(t1 - t0) / (s1 - s0);
	CHECK_NE(t0, t1);
	CHECK_NE(s0, s1);
}

}  // namespace zen