Initial commit
[csrprogrammer:csrremote.git] / stopwatch.cpp
1 #include "stopwatch.h"
2
3 StopWatch::StopWatch() :
4     started(false)
5 {
6 }
7
8 void StopWatch::start(void)
9 {
10     started = true;
11     clock_gettime(CLOCK_MONOTONIC, &starttime);
12 }
13
14 long StopWatch::elapsedmsec(void)
15 {
16     if(!started) return -1;
17
18     timespec tmp;
19     clock_gettime(CLOCK_MONOTONIC, &tmp);
20     tmp = timedifference(starttime,tmp);
21     return tmp.tv_sec*1000+tmp.tv_nsec/1000000;
22 }
23
24 float StopWatch::elapsedsec(void)
25 {
26     if(!started) return -1;
27
28     timespec tmp;
29     clock_gettime(CLOCK_MONOTONIC, &tmp);
30     tmp = timedifference(starttime,tmp);
31     return tmp.tv_sec + (float)tmp.tv_nsec/1000000000;
32 }
33
34 timespec StopWatch::timedifference(timespec start, timespec end)
35 {
36     timespec temp;
37     if ((end.tv_nsec-start.tv_nsec)<0) {
38         temp.tv_sec = end.tv_sec-start.tv_sec-1;
39         temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
40     } else {
41         temp.tv_sec = end.tv_sec-start.tv_sec;
42         temp.tv_nsec = end.tv_nsec-start.tv_nsec;
43     }
44     return temp;
45 }