3 #ifdef MADARA_FEATURE_SIMTIME
12 const double minrate = 0.0000000001;
14 std::mutex SimTime::mutex_{};
16 sim_time_callback_fn SimTime::callback_ =
nullptr;
18 uint64_t SimTime::last_realtime_ = SimTime::realtime();
19 uint64_t SimTime::last_simtime_ = -1;
20 double SimTime::last_rate_ = 1.0;
22 uint64_t SimTime::realtime()
24 namespace sc = std::chrono;
25 auto now = sc::steady_clock::now();
26 auto dur = now.time_since_epoch();
27 return sc::duration_cast<sc::nanoseconds>(dur).count();
30 uint64_t SimTime::realtime(uint64_t simtime)
35 sim_time_callback_fn callback;
38 std::lock_guard<std::mutex> guard{mutex_};
47 prt = last_realtime_ = realtime();
48 pst = last_simtime_ = st;
59 if (pst == (uint64_t)-1)
69 return ((simtime - pst) / pr) + prt;
72 uint64_t SimTime::time()
79 sim_time_callback_fn callback;
81 int64_t now = realtime();
83 std::lock_guard<std::mutex> guard{mutex_};
103 if (pst == (uint64_t)-1)
112 int64_t offset = now - prt;
119 double delta = offset * pr;
120 st = pst + (int64_t)delta;
126 double SimTime::rate()
129 sim_time_callback_fn callback;
132 std::lock_guard<std::mutex> guard{mutex_};
133 callback = callback_;
137 callback(
nullptr, &r);
148 uint64_t SimTime::duration(uint64_t sim_duration)
157 return sim_duration / r;
160 uint64_t SimTime::future(uint64_t sim_offset)
162 uint64_t now = realtime();
163 uint64_t offset = duration(sim_offset);
165 if (offset == (uint64_t)-1)
173 sim_time_callback_fn set_sim_time_callback(sim_time_callback_fn fn)
175 std::lock_guard<std::mutex> guard{SimTime::mutex_};
177 swap(fn, SimTime::callback_);
181 void sim_time_notify(uint64_t time,
double rate)
183 bool update_time = time != (uint64_t)-1;
184 bool update_rate = !std::isnan(rate);
186 if (!update_time && !update_rate)
191 uint64_t now = SimTime::realtime();
192 std::lock_guard<std::mutex> guard{SimTime::mutex_};
196 SimTime::last_realtime_ = now;
197 SimTime::last_simtime_ = time;
199 else if (SimTime::last_simtime_ == (uint64_t)-1)
201 SimTime::last_realtime_ = now;
202 SimTime::last_simtime_ = now;
207 SimTime::last_rate_ = rate;
Provides utility functions and classes for common tasks and needs.
Copyright(c) 2020 Galois.