summaryrefslogtreecommitdiffhomepage
path: root/opentrack-compat/timer.hpp
diff options
context:
space:
mode:
authorStanislaw Halik <sthalik@misaki.pl>2015-07-25 07:27:03 +0200
committerStanislaw Halik <sthalik@misaki.pl>2015-07-25 07:49:19 +0200
commit24538cf3a3a91481851618791b11be81437563e4 (patch)
tree4bcc9b97721170829038fe778633382c3e8754bc /opentrack-compat/timer.hpp
parent0f445ac2661b5454d491936bb780196b13d1f4ea (diff)
move portability classes to compat library
Diffstat (limited to 'opentrack-compat/timer.hpp')
-rw-r--r--opentrack-compat/timer.hpp75
1 files changed, 75 insertions, 0 deletions
diff --git a/opentrack-compat/timer.hpp b/opentrack-compat/timer.hpp
new file mode 100644
index 00000000..fd710499
--- /dev/null
+++ b/opentrack-compat/timer.hpp
@@ -0,0 +1,75 @@
+/* Copyright (c) 2014-2015, Stanislaw Halik <sthalik@misaki.pl>
+
+ * Permission to use, copy, modify, and/or distribute this
+ * software for any purpose with or without fee is hereby granted,
+ * provided that the above copyright notice and this permission
+ * notice appear in all copies.
+ */
+
+#pragma once
+#include <ctime>
+#if defined (_WIN32)
+# include <windows.h>
+# ifndef CLOCK_MONOTONIC
+# define CLOCK_MONOTONIC -1
+# endif
+static inline void opentrack_clock_gettime(int, struct timespec* ts)
+{
+ static LARGE_INTEGER freq;
+
+ if (!freq.QuadPart)
+ (void) QueryPerformanceFrequency(&freq);
+
+ LARGE_INTEGER d;
+
+ (void) QueryPerformanceCounter(&d);
+
+ d.QuadPart *= 1000000000L;
+ d.QuadPart /= freq.QuadPart;
+
+ ts->tv_sec = d.QuadPart / 1000000000L;
+ ts->tv_nsec = d.QuadPart % 1000000000L;
+}
+# define clock_gettime opentrack_clock_gettime
+#else
+# if defined(__MACH__)
+# define CLOCK_MONOTONIC 0
+# include <inttypes.h>
+# include <mach/mach_time.h>
+static inline void clock_gettime(int, struct timespec* ts)
+{
+ static mach_timebase_info_data_t sTimebaseInfo;
+ uint64_t state, nsec;
+ if ( sTimebaseInfo.denom == 0 ) {
+ (void) mach_timebase_info(&sTimebaseInfo);
+ }
+ state = mach_absolute_time();
+ nsec = state * sTimebaseInfo.numer / sTimebaseInfo.denom;
+ ts->tv_sec = nsec / 1000000000L;
+ ts->tv_nsec = nsec % 1000000000L;
+}
+# endif
+#endif
+class Timer {
+private:
+ struct timespec state;
+ long conv(const struct timespec& cur)
+ {
+ return (cur.tv_sec - state.tv_sec) * 1000000000L + (cur.tv_nsec - state.tv_nsec);
+ }
+public:
+ Timer() {
+ start();
+ }
+ void start() {
+ (void) clock_gettime(CLOCK_MONOTONIC, &state);
+ }
+ long elapsed() {
+ struct timespec cur;
+ (void) clock_gettime(CLOCK_MONOTONIC, &cur);
+ return conv(cur);
+ }
+ long elapsed_ms() {
+ return elapsed() / 1000000L;
+ }
+};