1 | // -*- c++ -*- |
---|
2 | #ifndef TIME_MEASURE_H |
---|
3 | #define TIME_MEASURE_H |
---|
4 | |
---|
5 | #include <sys/time.h> |
---|
6 | #include <sys/times.h> |
---|
7 | #include <fstream> |
---|
8 | #include <iostream> |
---|
9 | |
---|
10 | double currTime() { |
---|
11 | timeval tv; |
---|
12 | //timezone tz; |
---|
13 | gettimeofday(&tv, 0); |
---|
14 | return double(tv.tv_sec)+double(tv.tv_usec)/1000000.0; |
---|
15 | } |
---|
16 | |
---|
17 | class TimeStamp |
---|
18 | { |
---|
19 | tms ts; |
---|
20 | public: |
---|
21 | |
---|
22 | tms &getTms() {return ts;} |
---|
23 | const tms &getTms() const {return ts;} |
---|
24 | |
---|
25 | void stamp() {times(&ts);} |
---|
26 | TimeStamp() { ts.tms_utime=ts.tms_stime=ts.tms_cutime=ts.tms_cstime=0;} |
---|
27 | TimeStamp(void *) { stamp();} |
---|
28 | |
---|
29 | TimeStamp &operator+=(const TimeStamp &b) |
---|
30 | { |
---|
31 | ts.tms_utime+=b.ts.tms_utime; |
---|
32 | ts.tms_stime+=b.ts.tms_stime; |
---|
33 | ts.tms_cutime+=b.ts.tms_cutime; |
---|
34 | ts.tms_cstime+=b.ts.tms_cstime; |
---|
35 | return *this; |
---|
36 | } |
---|
37 | TimeStamp operator+(const TimeStamp &b) const |
---|
38 | { |
---|
39 | TimeStamp t(*this); |
---|
40 | return t+=b; |
---|
41 | } |
---|
42 | TimeStamp &operator-=(const TimeStamp &b) |
---|
43 | { |
---|
44 | ts.tms_utime-=b.ts.tms_utime; |
---|
45 | ts.tms_stime-=b.ts.tms_stime; |
---|
46 | ts.tms_cutime-=b.ts.tms_cutime; |
---|
47 | ts.tms_cstime-=b.ts.tms_cstime; |
---|
48 | return *this; |
---|
49 | } |
---|
50 | TimeStamp operator-(const TimeStamp &b) const |
---|
51 | { |
---|
52 | TimeStamp t(*this); |
---|
53 | return t-=b; |
---|
54 | } |
---|
55 | |
---|
56 | TimeStamp Ellapsed() const |
---|
57 | { |
---|
58 | TimeStamp t(NULL); |
---|
59 | return t-*this; |
---|
60 | } |
---|
61 | |
---|
62 | friend std::ostream& operator<<(std::ostream& os,const TimeStamp &t); |
---|
63 | |
---|
64 | }; |
---|
65 | |
---|
66 | class Timer |
---|
67 | { |
---|
68 | TimeStamp start_time; |
---|
69 | |
---|
70 | public: |
---|
71 | void reset() {start_time.stamp();} |
---|
72 | Timer() {reset();} |
---|
73 | |
---|
74 | operator TimeStamp () |
---|
75 | { |
---|
76 | TimeStamp t; |
---|
77 | t.stamp(); |
---|
78 | return t-start_time; |
---|
79 | } |
---|
80 | }; |
---|
81 | |
---|
82 | inline std::ostream& operator<<(std::ostream& os,const TimeStamp &t) |
---|
83 | { |
---|
84 | long cls = sysconf(_SC_CLK_TCK); |
---|
85 | os << "[ u: " << double(t.getTms().tms_utime)/cls << |
---|
86 | "s, s: " << double(t.getTms().tms_stime)/cls << |
---|
87 | "s, cu: " << double(t.getTms().tms_cutime)/cls << |
---|
88 | "s, cs: " << double(t.getTms().tms_cstime)/cls << "s ]"; |
---|
89 | return os; |
---|
90 | } |
---|
91 | |
---|
92 | #endif //TIME_MEASURE_H |
---|