goat3dgfx

view src/timer.cc @ 29:9d581abd0bfb

merged
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 02 Mar 2014 02:18:15 +0200
parents 1873dfd13f2d
children
line source
1 #include "timer.h"
3 using namespace goatgfx;
5 #if defined(__APPLE__) && !defined(__unix__)
6 #define __unix__
7 #endif
9 namespace goatgfx {
11 #ifdef __unix__
12 #include <time.h>
13 #include <unistd.h>
14 #include <sys/time.h>
16 #ifdef CLOCK_MONOTONIC
17 unsigned long get_time_msec(void)
18 {
19 struct timespec ts;
20 static struct timespec ts0;
22 clock_gettime(CLOCK_MONOTONIC, &ts);
23 if(ts0.tv_sec == 0 && ts0.tv_nsec == 0) {
24 ts0 = ts;
25 return 0;
26 }
27 return (ts.tv_sec - ts0.tv_sec) * 1000 + (ts.tv_nsec - ts0.tv_nsec) / 1000000;
28 }
29 #else /* no fancy POSIX clocks, fallback to good'ol gettimeofday */
30 unsigned long get_time_msec(void)
31 {
32 struct timeval tv;
33 static struct timeval tv0;
35 gettimeofday(&tv, 0);
36 if(tv0.tv_sec == 0 && tv0.tv_usec == 0) {
37 tv0 = tv;
38 return 0;
39 }
40 return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
41 }
42 #endif /* !posix clock */
44 void sleep_msec(unsigned long msec)
45 {
46 usleep(msec * 1000);
47 }
48 #endif
50 #ifdef WIN32
51 #include <windows.h>
52 #pragma comment(lib, "winmm.lib")
54 unsigned long get_time_msec(void)
55 {
56 return timeGetTime();
57 }
59 void sleep_msec(unsigned long msec)
60 {
61 Sleep(msec);
62 }
63 #endif
65 double get_time_sec(void)
66 {
67 return get_time_msec() / 1000.0f;
68 }
70 void sleep_sec(double sec)
71 {
72 if(sec > 0.0f) {
73 sleep_msec(sec * 1000.0f);
74 }
75 }
77 } // namespace goatgfx
80 Timer::Timer()
81 {
82 reset();
83 }
85 void Timer::reset()
86 {
87 pause_time = 0;
88 start_time = get_time_msec();
89 }
91 void Timer::start()
92 {
93 if(!is_running()) {
94 // resuming
95 start_time += get_time_msec() - pause_time;
96 pause_time = 0;
97 }
98 }
100 void Timer::stop()
101 {
102 if(is_running()) {
103 pause_time = get_time_msec();
104 }
105 }
107 bool Timer::is_running() const
108 {
109 return pause_time == 0;
110 }
112 unsigned long Timer::get_msec() const
113 {
114 if(!is_running()) {
115 // in paused state...
116 return pause_time - start_time;
117 }
118 return get_time_msec() - start_time;
119 }
121 double Timer::get_sec() const
122 {
123 return (double)get_msec() / 1000.0;
124 }