Imported Upstream version 0.12.7
[bowtie.git] / timer.h
1 #ifndef TIMER_H_
2 #define TIMER_H_
3
4 #include <ctime>
5 #include <iostream>
6 #include <iomanip>
7
8 using namespace std;
9
10 /**
11  * Use time() call to keep track of elapsed time between creation and
12  * destruction.  If verbose is true, Timer will print a message showing
13  * elapsed time to the given output stream upon destruction.
14  */
15 class Timer {
16 public:
17         Timer(ostream& out = cout, const char *msg = "", bool verbose = true) :
18                 _t(time(0)), _out(out), _msg(msg), _verbose(verbose) { }
19
20         /// Optionally print message
21         ~Timer() {
22                 if(_verbose) write(_out);
23         }
24         
25         /// Return elapsed time since Timer object was created
26         time_t elapsed() const {
27                 return time(0) - _t;
28         }
29         
30         void write(ostream& out) {
31                 time_t passed = elapsed();
32                 // Print the message supplied at construction time followed
33                 // by time elapsed formatted HH:MM:SS 
34                 unsigned int hours   = (passed / 60) / 60;
35                 unsigned int minutes = (passed / 60) % 60;
36                 unsigned int seconds = (passed % 60);
37                 out << _msg << setfill ('0') << setw (2) << hours << ":"
38                             << setfill ('0') << setw (2) << minutes << ":"
39                             << setfill ('0') << setw (2) << seconds << endl;
40         }
41         
42 private:
43         time_t      _t;
44         ostream&    _out;
45         const char *_msg;
46         bool        _verbose;
47 };
48
49 static inline void logTime(std::ostream& os, bool nl = true) {
50         struct tm *current;
51         time_t now;
52         time(&now);
53         current = localtime(&now);
54         os << setfill('0') << setw(2)
55             << current->tm_hour << ":"
56             << setfill('0') << setw(2)
57             << current->tm_min << ":"
58             << setfill('0') << setw(2)
59             << current->tm_sec;
60         if(nl) os << std::endl;
61 }
62
63 #endif /*TIMER_H_*/