libecs-cpp 2.1.0
Entity Component System library in C++
Loading...
Searching...
No Matches
Clock.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <atomic>
4#include <chrono>
5#include <cstdint>
6#include <stdexcept>
7#include <string>
8
9namespace ecs
10{
20 class Clock
21 {
22 public:
24 virtual ~Clock() = default;
26 virtual std::chrono::microseconds Now() const = 0;
27 };
28
31 class SteadyClock : public Clock
32 {
33 public:
34 std::chrono::microseconds Now() const override
35 {
36 return std::chrono::duration_cast<std::chrono::microseconds>(
37 std::chrono::steady_clock::now().time_since_epoch());
38 }
39
41 static const SteadyClock &Instance()
42 {
43 static const SteadyClock instance;
44 return instance;
45 }
46 };
47
51 class ManualClock : public Clock
52 {
53 public:
55 explicit ManualClock(std::chrono::microseconds start = std::chrono::microseconds(0))
56 : count(start.count())
57 {
58 }
59
60 std::chrono::microseconds Now() const override
61 {
62 return std::chrono::microseconds(this->count.load());
63 }
64
66 void Advance(std::chrono::microseconds delta)
67 {
68 if(delta.count() < 0)
69 {
70 throw std::runtime_error("ecs::ManualClock::Advance(): a clock cannot move backwards (" +
71 std::to_string(delta.count()) + " us).");
72 }
73 this->count.fetch_add(delta.count());
74 }
75
77 void Set(std::chrono::microseconds value)
78 {
79 this->count.store(value.count());
80 }
81
82 private:
83 std::atomic<int64_t> count;
84 };
85}
A source of time for systems and containers.
Definition Clock.hpp:21
virtual std::chrono::microseconds Now() const =0
Time since the clock's starting point, in microseconds.
virtual ~Clock()=default
Destroys the clock.
A clock that only moves when told to, for tests.
Definition Clock.hpp:52
ManualClock(std::chrono::microseconds start=std::chrono::microseconds(0))
Creates a clock that reads the given time, zero by default.
Definition Clock.hpp:55
std::chrono::microseconds Now() const override
Time since the clock's starting point, in microseconds.
Definition Clock.hpp:60
void Advance(std::chrono::microseconds delta)
Moves time forward.
Definition Clock.hpp:66
void Set(std::chrono::microseconds value)
Sets the time.
Definition Clock.hpp:77
The real clock: std::chrono::steady_clock, truncated to whole microseconds.
Definition Clock.hpp:32
static const SteadyClock & Instance()
The shared instance, which lives until the process ends.
Definition Clock.hpp:41
std::chrono::microseconds Now() const override
Time since the clock's starting point, in microseconds.
Definition Clock.hpp:34
Definition Clock.hpp:10