win32 mingw fixes
[laserbrain_demo] / src / timer.cc
1 #include "timer.h"
2
3 #if defined(__APPLE__) && !defined(__unix__)
4 #define __unix__
5 #endif
6
7 #ifdef __unix__
8 #include <time.h>
9 #include <unistd.h>
10 #include <sys/time.h>
11
12 #ifdef CLOCK_MONOTONIC
13 unsigned long get_time_msec(void)
14 {
15         struct timespec ts;
16         static struct timespec ts0;
17
18         clock_gettime(CLOCK_MONOTONIC, &ts);
19         if(ts0.tv_sec == 0 && ts0.tv_nsec == 0) {
20                 ts0 = ts;
21                 return 0;
22         }
23         return (ts.tv_sec - ts0.tv_sec) * 1000 + (ts.tv_nsec - ts0.tv_nsec) / 1000000;
24 }
25 #else   /* no fancy POSIX clocks, fallback to good'ol gettimeofday */
26 unsigned long get_time_msec(void)
27 {
28         struct timeval tv;
29         static struct timeval tv0;
30
31         gettimeofday(&tv, 0);
32         if(tv0.tv_sec == 0 && tv0.tv_usec == 0) {
33                 tv0 = tv;
34                 return 0;
35         }
36         return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000;
37 }
38 #endif  /* !posix clock */
39
40 void sleep_msec(unsigned long msec)
41 {
42         usleep(msec * 1000);
43 }
44 #endif
45
46 #if defined(WIN32) || defined(__WIN32__)
47 #include <windows.h>
48 #ifdef _MSC_VER
49 #pragma comment(lib, "winmm.lib")
50 #endif
51
52 unsigned long get_time_msec(void)
53 {
54         return timeGetTime();
55 }
56
57 void sleep_msec(unsigned long msec)
58 {
59         Sleep(msec);
60 }
61 #endif
62
63 double get_time_sec(void)
64 {
65         return get_time_msec() / 1000.0f;
66 }
67
68 void sleep_sec(double sec)
69 {
70         if(sec > 0.0f) {
71                 sleep_msec(sec * 1000.0f);
72         }
73 }
74
75
76 Timer::Timer()
77 {
78         reset();
79 }
80
81 void Timer::reset()
82 {
83         pause_time = 0;
84         start_time = get_time_msec();
85 }
86
87 void Timer::start()
88 {
89         if(!is_running()) {
90                 // resuming
91                 start_time += get_time_msec() - pause_time;
92                 pause_time = 0;
93         }
94 }
95
96 void Timer::stop()
97 {
98         if(is_running()) {
99                 pause_time = get_time_msec();
100         }
101 }
102
103 bool Timer::is_running() const
104 {
105         return pause_time == 0;
106 }
107
108 unsigned long Timer::get_msec() const
109 {
110         if(!is_running()) {
111                 // in paused state...
112                 return pause_time - start_time;
113         }
114         return get_time_msec() - start_time;
115 }
116
117 double Timer::get_sec() const
118 {
119         return (double)get_msec() / 1000.0;
120 }