issue#11: cds: changed __CDS_ guard prefix to CDSLIB_ for all .h files
[libcds.git] / cds / os / linux / timer.h
1 //$$CDS-header$$
2
3 #ifndef CDSLIB_OS_LINUX_TIMER_H
4 #define CDSLIB_OS_LINUX_TIMER_H
5
6 #ifndef CDSLIB_OS_TIMER_H
7 #   error "<cds/os/timer.h> must be included"
8 #endif
9
10 #include <time.h>
11 //#include <sys/time.h>
12
13 //@cond none
14 namespace cds { namespace OS {
15     CDS_CXX11_INLINE_NAMESPACE namespace Linux {
16
17         // High resolution timer
18         class Timer {
19         public:
20             typedef struct timespec native_timer_type;
21             typedef long long       native_duration_type;
22
23         private:
24             native_timer_type    m_tmStart;
25
26         public:
27
28             Timer() { current( m_tmStart ) ; }
29
30             static void current( native_timer_type& tmr )
31             {
32                 // faster than gettimeofday() and posix
33                 clock_gettime( CLOCK_REALTIME, &tmr );
34             }
35
36             static native_timer_type    current()
37             {
38                 native_timer_type    tmr;
39                 current(tmr);
40                 return tmr;
41             }
42
43             double reset()
44             {
45                 native_timer_type ts;
46                 current( ts );
47                 double dblRet = ( ts.tv_sec - m_tmStart.tv_sec ) + ( ts.tv_nsec - m_tmStart.tv_nsec ) / 1.0E9;
48                 m_tmStart = ts;
49                 return dblRet;
50             }
51
52             double duration( native_duration_type dur )
53             {
54                 return double( dur ) / 1.0E9;
55             }
56
57             double duration()
58             {
59                 return duration( native_duration() );
60             }
61
62             native_duration_type    native_duration()
63             {
64                 native_timer_type ts;
65                 current( ts );
66                 return native_duration( m_tmStart, ts );
67             }
68
69             static native_duration_type    native_duration( const native_timer_type& nStart, const native_timer_type& nEnd )
70             {
71                 return native_duration_type( nEnd.tv_sec - nStart.tv_sec ) * 1000000000 + ( nEnd.tv_nsec - nStart.tv_nsec);
72             }
73
74             static unsigned long long random_seed()
75             {
76                 native_timer_type tmr;
77                 current( tmr );
78                 return ( ((unsigned long long)(tmr.tv_sec)) << 32 ) + tmr.tv_nsec;
79             }
80         };
81     }    // namespace Linux
82
83 #ifndef CDS_CXX11_INLINE_NAMESPACE_SUPPORT
84     typedef Linux::Timer    Timer;
85 #endif
86
87 }}    // namespace cds::OS
88 //@endcond
89
90 #endif // #ifndef CDSLIB_OS_LINUX_TIMER_H