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