~
[scx.git] / include / RunTimer.hpp
blobd558409dd7930d217e1a7d0a1e4fddf0937f6e5d
1 #ifndef SCX_RUNTIMER_HPP
2 #define SCX_RUNTIMER_HPP
4 #include <iostream>
5 #include <time.h>
6 #ifdef __MACH__
7 #include <mach/clock.h>
8 #include <mach/mach.h>
9 #endif
11 #define SCX_BENCH(tag, times, loops, i, j, \
12 onLoop, \
13 beforeStart, afterStart, \
14 beforeStop, afterStop) \
15 { \
16 scx::RunTimer scx_timer; \
17 double scx_sum = 0; \
18 for (int i = 0; i < times; ++i) { \
19 beforeStart; \
20 scx_timer.Start(); \
21 afterStart; \
22 for (int j = 0; j < loops; ++j) { \
23 onLoop; \
24 } \
25 beforeStop; \
26 scx_timer.Stop(); \
27 scx_sum += scx_timer.DiffMS(); \
28 afterStop; \
29 } \
30 std::cout << tag << (scx_sum / times) << std::endl; \
31 }; class __END__
33 #define SCX_BENCH0(tag, times, count, onLoop) \
34 SCX_BENCH(tag, times, count, i, j, \
35 onLoop, \
36 , , \
37 , )
39 #define SCX_BENCH1(tag, times, count, onLoop, \
40 beforeStart) \
41 SCX_BENCH(tag, times, count, i, j, \
42 onLoop, \
43 beforeStart, , \
44 , )
46 #define SCX_BENCH4(tag, times, count, onLoop, \
47 afterStop) \
48 SCX_BENCH(tag, times, count, i, j, \
49 onLoop, \
50 , , \
51 , afterStop)
53 #define SCX_BENCH14(tag, times, count, onLoop, \
54 beforeStart, afterStop) \
55 SCX_BENCH(tag, times, count, i, j, \
56 onLoop, \
57 beforeStart, , \
58 , afterStop)
60 namespace scx {
62 class RunTimer
64 public:
65 void Start()
67 #ifdef __MACH__
68 clock_serv_t cclock;
69 mach_timespec_t mts;
70 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
71 clock_get_time(cclock, &mts);
72 mach_port_deallocate(mach_task_self(), cclock);
73 mBegin.tv_sec = mts.tv_sec;
74 mBegin.tv_nsec = mts.tv_nsec;
75 #else
76 clock_gettime(CLOCK_MONOTONIC_PRECISE, &mBegin);
77 #endif
80 void Stop()
82 #ifdef __MACH__
83 clock_serv_t cclock;
84 mach_timespec_t mts;
85 host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
86 clock_get_time(cclock, &mts);
87 mach_port_deallocate(mach_task_self(), cclock);
88 mEnd.tv_sec = mts.tv_sec;
89 mEnd.tv_nsec = mts.tv_nsec;
90 #else
91 clock_gettime(CLOCK_MONOTONIC_PRECISE, &mEnd);
92 #endif
95 void PrintMS() const
97 std::cout << (time_t)DiffMS() << std::endl;
100 void PrintUS() const
102 std::cout << (time_t)DiffUS() << std::endl;
105 double DiffMS() const
107 return DiffUS() / 1000.f;
110 double DiffUS() const
112 return (mEnd.tv_sec - mBegin.tv_sec)*1000000.f + (mEnd.tv_nsec - mBegin.tv_nsec)/1000.f;
115 private:
116 timespec mBegin;
117 timespec mEnd;
122 #endif