Go to the documentation of this file.00001
00002
00003
00004
00005
00006
00013 #ifndef MEASURE_TIME_H
00014 #define MEASURE_TIME_H
00015
00016 #include "io-lock.h"
00017 #include <string>
00018
00019 enum time_unit {sec, ms, us, ns, unspecified};
00020
00021 static inline void display_resolution_maybe () {
00022 static int granularity_displaid = 0;
00023 if (!granularity_displaid) {
00024 struct timespec t;
00025 clock_getres(CLOCK_REALTIME, &t);
00026 L_COUT << "// TEST-IGNORE: granularity CLOCK_REALTIME = "
00027 << (t.tv_sec * 1e9) + t.tv_nsec
00028 << " nanoseconds" << std::endl;
00029 clock_getres(CLOCK_PROCESS_CPUTIME_ID, &t);
00030 L_COUT << "// TEST-IGNORE: granularity CLOCK_PROCESS_CPUTIME_ID = "
00031 << (t.tv_sec * 1e9) + t.tv_nsec
00032 << " nanoseconds" << std::endl;
00033 granularity_displaid = 1;
00034 }
00035 }
00036
00037 template<clockid_t ID>
00038 class delta_time {
00039 public:
00040 void start() {
00041 clock_gettime(ID, &m_start);
00042 }
00043
00044 void stop() {
00045 clock_gettime(ID, &m_stop);
00046 }
00047
00048 std::string to_string(time_unit u = unspecified) {
00049 std::stringstream s;
00050 double diff_sec = m_stop.tv_sec - m_start.tv_sec;
00051 double diff_nsec = m_stop.tv_nsec - m_start.tv_nsec;
00052 double diff = diff_sec + (diff_nsec/1e9);
00053 if (u == unspecified) {
00054 if (diff > 1) {
00055 u = sec;
00056 } else if (diff*1e3 > 1) {
00057 u = ms;
00058 } else if (diff*1e6 > 1) {
00059 u = us;
00060 } else {
00061 u = ns;
00062 }
00063 }
00064 switch (u) {
00065 case sec:
00066 s << diff << " sec";
00067 break;
00068 case ms:
00069 s << diff*1e3 << " ms";
00070 break;
00071 case us:
00072 s << diff*1e6 << " us";
00073 break;
00074 case ns:
00075 s << diff*1e9 << " ns";
00076 break;
00077 default: abort();
00078 }
00079 return s.str();
00080 }
00081
00082 private:
00083 struct timespec m_start;
00084 struct timespec m_stop;
00085 };
00086
00088 class measure_time {
00089 public:
00090 measure_time() : m_unit(unspecified)
00091 {
00092 start_measures();
00093 }
00094 measure_time(std::string message, time_unit u = unspecified) :
00095 m_message(message),
00096 m_unit(u) {
00097 L_COUT << "// TEST-IGNORE: start measuring " + message << std::endl;
00098 start_measures();
00099 }
00100
00101 ~measure_time() {
00102 real.stop(); cpu.stop(); this_thread.stop();
00103 L_COUT << "// TEST-IGNORE: time[" << m_message << "] = "
00104 << real.to_string(m_unit) << " real, "
00105 << cpu.to_string(m_unit) << " CPU, "
00106 << this_thread.to_string(m_unit) << " CPU (this thread)."
00107 << std::endl;
00108 }
00109
00110 void start_measures() {
00111
00112 real.start(); cpu.start(); this_thread.start();
00113 }
00114
00115
00116 private:
00117 std::string m_message;
00118 time_unit m_unit;
00119 delta_time<CLOCK_REALTIME> real;
00120 delta_time<CLOCK_PROCESS_CPUTIME_ID> cpu;
00121 delta_time<CLOCK_THREAD_CPUTIME_ID> this_thread;
00122 };
00123
00124 #endif // MEASURE_TIME_H