]> AND Private Git Repository - loba.git/blob - timer.h
Logo AND Algorithmique Numérique Distribuée

Private GIT Repository
Initial commit.
[loba.git] / timer.h
1 #ifndef TIMER_H
2 #define TIMER_H
3
4 #include <sys/time.h>
5 #include <sys/resource.h>
6
7 #if NEED_TIMERCLEAR
8 inline
9 void timerclear(struct timeval& a)
10 {
11     tv.sec = tv.usec = 0;
12 }
13 #endif
14
15 inline
16 struct timeval operator+(const struct timeval& a, const struct timeval& b)
17 {
18     struct timeval result;
19     result.tv_sec = a.tv_sec + b.tv_sec;
20     result.tv_usec = a.tv_usec + b.tv_usec;
21     if (result.tv_usec >= 1000000) {
22         ++result.tv_sec;
23         result.tv_usec -= 1000000;
24     }
25     return result;
26 }
27
28 inline
29 struct timeval operator-(const struct timeval& a, const struct timeval& b)
30 {
31     timeval result;
32     result.tv_sec = a.tv_sec - b.tv_sec;
33     result.tv_usec = a.tv_usec - b.tv_usec;
34     if (result.tv_usec < 0) {
35         -- result.tv_sec;
36         result.tv_usec += 1000000;
37     }
38     return result;
39 }
40
41 double timertod(const timeval& a)
42 {
43     return a.tv_sec + a.tv_usec / 1e6;
44 }
45
46 class timestamp {
47 private:
48     struct rusage before;
49     struct rusage after;
50     struct timeval difference;
51
52 public:
53     timestamp()
54     {
55         reset();
56     }
57
58     void reset()
59     {
60         timerclear(&before.ru_utime);
61         timerclear(&before.ru_stime);
62         timerclear(&after.ru_utime);
63         timerclear(&after.ru_stime);
64         timerclear(&difference);
65     }
66
67     void start()
68     {
69         getrusage(RUSAGE_SELF, &before);        
70     }
71
72     void stop()
73     {
74         getrusage(RUSAGE_SELF, &after);        
75         difference = difference + ((after.ru_utime + after.ru_stime) -
76                                    (before.ru_utime + before.ru_stime));
77     }
78
79     struct timeval tv_duration() const
80     {
81         return difference;
82     }
83
84     double duration() const
85     {
86         return timertod(difference);
87     }
88 };
89
90 #endif // !TIMER_H
91
92 // Local variables:
93 // mode: c++
94 // End: