-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathtimer.h
More file actions
94 lines (82 loc) · 2.85 KB
/
timer.h
File metadata and controls
94 lines (82 loc) · 2.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//---------------------------------------------------------
// Timer.h
//---------------------------------------------------------
#ifndef __TIMER_H__
#define __TIMER_H__
#include <time.h>
#include <sys/time.h>
#include <string.h>
#include <stdio.h>
#define TIMER_ON
//---------------------------------------------------------
// Timer is an object which helps profile programs using
// the clock() function.
// - By default, a timer is stopped when you instantiate it
// and must be started manually
// - Passing True to the constructor starts the timer when
// it is constructed
// - When the timer is destructed it prints stats to stdout
//---------------------------------------------------------
class Timer {
#ifdef TIMER_ON
char binName[50];
unsigned nCalls;
timeval ts_start;
float totalTime;
public:
//------------------------------------------------------------------
// constructor
//------------------------------------------------------------------
Timer (const char* Name="", bool On=false) {
if (On) {
// record the start time
gettimeofday(&ts_start, NULL);
nCalls = 1;
}
else {
nCalls = 0;
}
totalTime = 0;
strcpy(binName, Name);
}
//------------------------------------------------------------------
// destructor
//------------------------------------------------------------------
~Timer () {
// on being destroyed, print the average and total time
if (nCalls > 0) {
printf ("%-20s: ", binName);
printf ("%6d calls; ", nCalls);
printf ("%7.3f msecs total time\n", 1000*totalTime);
//printf ("%7.4f msecs average time;\n", 1000*totalTime/nCalls);
}
}
//------------------------------------------------------------------
// start timer
//------------------------------------------------------------------
void start() {
// record start time
gettimeofday(&ts_start, NULL);
nCalls++;
}
//------------------------------------------------------------------
// stop timer
//------------------------------------------------------------------
void stop() {
// get current time, add elapsed time to totalTime
timeval ts_curr;
gettimeofday(&ts_curr, NULL);
totalTime += float(ts_curr.tv_sec - ts_start.tv_sec) +
float(ts_curr.tv_usec)*1e-6 - float(ts_start.tv_usec)*1e-6;
}
#else
//--------------------------------------------------------------------
// all methods do nothing if TIMER_ON is not set
//--------------------------------------------------------------------
public:
Timer (const char* Name, bool On=true) {}
void start() {}
void stop() {}
#endif
};
#endif