Ion
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
timer.cc
Go to the documentation of this file.
1 
18 #include "ion/port/timer.h"
19 
20 #if defined(ION_PLATFORM_WINDOWS)
21 #include <Windows.h> // NOLINT
22 #else
23 #include <unistd.h>
24 #endif
25 
26 #include <atomic>
27 
28 namespace ion {
29 namespace port {
30 
31 #if defined(ION_PLATFORM_WINDOWS)
32 Timer::steady_clock::time_point Timer::steady_clock::now() {
40  static std::atomic<int64> s_freq;
43  int64 freq = s_freq.load(std::memory_order_relaxed);
44  if (freq == 0) {
45  LARGE_INTEGER li_freq;
46  QueryPerformanceFrequency(&li_freq);
47  freq = li_freq.QuadPart;
50  s_freq.store(freq, std::memory_order_relaxed);
51  }
52 
53  LARGE_INTEGER pc;
54  QueryPerformanceCounter(&pc);
55  const int64 counter = pc.QuadPart;
56  const int64 sec = (counter / freq) * period::den / period::num;
57  const int64 nano = (counter % freq) * period::den / freq / period::num;
58  return time_point(duration(sec + nano));
59 }
60 
62 void Timer::SleepNSeconds(unsigned int seconds) { Sleep(seconds * 1000); }
63 
65 void Timer::SleepNMilliseconds(unsigned int milliseconds) {
66  Sleep(milliseconds);
67 }
68 
69 #else
70 void Timer::SleepNSeconds(unsigned int seconds) { sleep(seconds); }
72 
74 void Timer::SleepNMilliseconds(unsigned int milliseconds) {
75  const int millis = static_cast<int>(milliseconds);
76  const struct timespec sleeptime = {millis / 1000, (millis % 1000) * 1000000};
77  struct timespec remaining = {0, 0};
78  nanosleep(&sleeptime, &remaining);
79 }
80 
81 #endif
82 
83 void Timer::Reset() { start_ = Clock::now(); }
84 
85 Timer::Clock::duration Timer::Get() const { return Clock::now() - start_; }
86 
87 double Timer::GetInS() const {
88  return std::chrono::duration_cast<std::chrono::duration<double>>(Get())
89  .count();
90 }
91 
92 double Timer::GetInMs() const {
93  return std::chrono::duration_cast<std::chrono::duration<double, std::milli>>(
94  Get())
95  .count();
96 }
97 
98 } // namespace port
99 } // namespace ion
double GetInS() const
Returns the elapsed time since construction or the last Reset() in seconds.
Definition: timer.cc:87
double GetInMs() const
Returns the elapsed time since construction or the last Reset() in milliseconds.
Definition: timer.cc:92
static void SleepNSeconds(unsigned int seconds)
Sleeps for the passed number of seconds.
Definition: timer.cc:71
static void SleepNMilliseconds(unsigned int milliseconds)
Sleeps for n milliseconds.
Definition: timer.cc:74
void Reset()
Resets the timer.
Definition: timer.cc:83
Clock::duration Get() const
Returns the elapsed time since construction or the last Reset().
Definition: timer.cc:85