goat3dgfx

view src/timer.cc @ 10:b4c9a24c946e

wrote an awesome configure script added "main" 3d engine source file with global init/cleanup
author John Tsiombikas <nuclear@member.fsf.org>
date Sun, 24 Nov 2013 13:30:44 +0200
parents
children 7d6b667821cf
line source
1 #include "timer.h"
3 #if defined(__APPLE__) && !defined(__unix__)
4 #define __unix__
5 #endif
7 #ifdef __unix__
8 #include <time.h>
9 #include <unistd.h>
10 #include <sys/time.h>
12 #ifdef CLOCK_MONOTONIC
13 unsigned long get_time_msec(void)
14 {
15 struct timespec ts;
16 static struct timespec ts0;
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;
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 */
40 void sleep_msec(unsigned long msec)
41 {
42 usleep(msec * 1000);
43 }
44 #endif
46 #ifdef WIN32
47 #include <windows.h>
48 #pragma comment(lib, "winmm.lib")
50 unsigned long get_time_msec(void)
51 {
52 return timeGetTime();
53 }
55 void sleep_msec(unsigned long msec)
56 {
57 Sleep(msec);
58 }
59 #endif
61 double get_time_sec(void)
62 {
63 return get_time_msec() / 1000.0f;
64 }
66 void sleep_sec(double sec)
67 {
68 if(sec > 0.0f) {
69 sleep_msec(sec * 1000.0f);
70 }
71 }
74 Timer::Timer()
75 {
76 reset();
77 }
79 void Timer::reset()
80 {
81 pause_time = 0;
82 start_time = get_time_msec();
83 }
85 void Timer::start()
86 {
87 if(!is_running()) {
88 // resuming
89 start_time += get_time_msec() - pause_time;
90 pause_time = 0;
91 }
92 }
94 void Timer::stop()
95 {
96 if(is_running()) {
97 pause_time = get_time_msec();
98 }
99 }
101 bool Timer::is_running() const
102 {
103 return pause_time == 0;
104 }
106 unsigned long Timer::get_msec() const
107 {
108 if(!is_running()) {
109 // in paused state...
110 return pause_time - start_time;
111 }
112 return get_time_msec() - start_time;
113 }
115 double Timer::get_sec() const
116 {
117 return (double)get_msec() / 1000.0;
118 }