-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathclock.cc
82 lines (79 loc) · 1.87 KB
/
clock.cc
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
#include <chrono>
#include <mutex>
#include <condition_variable>
#include <thread>
static auto& GetRealStartTime()
{
static auto start = std::chrono::system_clock::now();
return start;
}
static double GetRealElapsed()
{
auto start = GetRealStartTime();
auto now = std::chrono::system_clock::now();
std::chrono::duration<double> dur = (now - start);
return dur.count();
}
static struct
{
double TimeFactor = 1.0;
double FakeTime = 0.0;
std::mutex lk;
std::condition_variable updated;
double Waiting = 0;
bool Terminated = false;
} data;
static thread_local double LastTime = 0.0;
double GetTime()
{
if(data.TimeFactor != 0.0)
{
return GetRealElapsed() * data.TimeFactor;
}
return data.FakeTime;
}
void AdvanceTime(double seconds)
{
data.FakeTime += seconds;
if(data.TimeFactor == 0.0)
{
if(data.Waiting != 0 && data.Waiting <= data.FakeTime)
{
{std::unique_lock<std::mutex> lock(data.lk);}
data.updated.notify_all();
}
LastTime = data.FakeTime;
}
}
void SleepFor(double seconds)
{
if(data.TimeFactor != 0.0)
{
std::this_thread::sleep_for(std::chrono::duration<double>(seconds / data.TimeFactor));
}
else
{
double until = LastTime+seconds;
if(data.FakeTime < until)
{
std::unique_lock<std::mutex> lock(data.lk);
data.Waiting = until;
if(data.FakeTime < until)
{
data.updated.wait(lock, [&]{ return data.FakeTime >= until || data.Terminated; });
}
data.Waiting = 0;
}
LastTime = until;
}
}
void SetTimeFactor(double factor)
{
data.TimeFactor = factor;
}
void TimeTerminate()
{
data.Terminated = true;
{std::unique_lock<std::mutex> lock(data.lk);}
data.updated.notify_all();
}