dbf-halloween2015
diff src/timer.cc @ 0:50683c78264e
initial commit
author | John Tsiombikas <nuclear@member.fsf.org> |
---|---|
date | Sun, 01 Nov 2015 00:09:12 +0200 |
parents | |
children |
line diff
1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/src/timer.cc Sun Nov 01 00:09:12 2015 +0200 1.3 @@ -0,0 +1,118 @@ 1.4 +#include "timer.h" 1.5 + 1.6 +#if defined(__APPLE__) && !defined(__unix__) 1.7 +#define __unix__ 1.8 +#endif 1.9 + 1.10 +#ifdef __unix__ 1.11 +#include <time.h> 1.12 +#include <unistd.h> 1.13 +#include <sys/time.h> 1.14 + 1.15 +#ifdef CLOCK_MONOTONIC 1.16 +unsigned long get_time_msec(void) 1.17 +{ 1.18 + struct timespec ts; 1.19 + static struct timespec ts0; 1.20 + 1.21 + clock_gettime(CLOCK_MONOTONIC, &ts); 1.22 + if(ts0.tv_sec == 0 && ts0.tv_nsec == 0) { 1.23 + ts0 = ts; 1.24 + return 0; 1.25 + } 1.26 + return (ts.tv_sec - ts0.tv_sec) * 1000 + (ts.tv_nsec - ts0.tv_nsec) / 1000000; 1.27 +} 1.28 +#else /* no fancy POSIX clocks, fallback to good'ol gettimeofday */ 1.29 +unsigned long get_time_msec(void) 1.30 +{ 1.31 + struct timeval tv; 1.32 + static struct timeval tv0; 1.33 + 1.34 + gettimeofday(&tv, 0); 1.35 + if(tv0.tv_sec == 0 && tv0.tv_usec == 0) { 1.36 + tv0 = tv; 1.37 + return 0; 1.38 + } 1.39 + return (tv.tv_sec - tv0.tv_sec) * 1000 + (tv.tv_usec - tv0.tv_usec) / 1000; 1.40 +} 1.41 +#endif /* !posix clock */ 1.42 + 1.43 +void sleep_msec(unsigned long msec) 1.44 +{ 1.45 + usleep(msec * 1000); 1.46 +} 1.47 +#endif 1.48 + 1.49 +#ifdef WIN32 1.50 +#include <windows.h> 1.51 +#pragma comment(lib, "winmm.lib") 1.52 + 1.53 +unsigned long get_time_msec(void) 1.54 +{ 1.55 + return timeGetTime(); 1.56 +} 1.57 + 1.58 +void sleep_msec(unsigned long msec) 1.59 +{ 1.60 + Sleep(msec); 1.61 +} 1.62 +#endif 1.63 + 1.64 +double get_time_sec(void) 1.65 +{ 1.66 + return get_time_msec() / 1000.0f; 1.67 +} 1.68 + 1.69 +void sleep_sec(double sec) 1.70 +{ 1.71 + if(sec > 0.0f) { 1.72 + sleep_msec(sec * 1000.0f); 1.73 + } 1.74 +} 1.75 + 1.76 + 1.77 +Timer::Timer() 1.78 +{ 1.79 + reset(); 1.80 +} 1.81 + 1.82 +void Timer::reset() 1.83 +{ 1.84 + pause_time = 0; 1.85 + start_time = get_time_msec(); 1.86 +} 1.87 + 1.88 +void Timer::start() 1.89 +{ 1.90 + if(!is_running()) { 1.91 + // resuming 1.92 + start_time += get_time_msec() - pause_time; 1.93 + pause_time = 0; 1.94 + } 1.95 +} 1.96 + 1.97 +void Timer::stop() 1.98 +{ 1.99 + if(is_running()) { 1.100 + pause_time = get_time_msec(); 1.101 + } 1.102 +} 1.103 + 1.104 +bool Timer::is_running() const 1.105 +{ 1.106 + return pause_time == 0; 1.107 +} 1.108 + 1.109 +unsigned long Timer::get_msec() const 1.110 +{ 1.111 + if(!is_running()) { 1.112 + // in paused state... 1.113 + return pause_time - start_time; 1.114 + } 1.115 + return get_time_msec() - start_time; 1.116 +} 1.117 + 1.118 +double Timer::get_sec() const 1.119 +{ 1.120 + return (double)get_msec() / 1000.0; 1.121 +}