Made cds::OS children namespaces inline, removed OS-specific syserror.h headers
[libcds.git] / cds / os / posix / timer.h
1 //$$CDS-header$$
2
3 #ifndef __CDS_OS_POSIX_TIMER_H
4 #define __CDS_OS_POSIX_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
12 //@cond none
13 namespace cds { namespace OS {
14     CDS_CXX11_INLINE_NAMESPACE namespace posix {
15
16         // High resolution timer
17         // From Linux as an example
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             Timer() { current( m_tmStart ) ; }
28
29             static void current( native_timer_type& tmr )
30             {
31                 // faster than gettimeofday() and posix
32                 clock_gettime( CLOCK_REALTIME, &tmr );
33             }
34
35             static native_timer_type    current()
36             {
37                 native_timer_type    tmr;
38                 current(tmr);
39                 return tmr;
40             }
41
42             double reset()
43             {
44                 native_timer_type ts;
45                 current( ts );
46                 double dblRet = ( ts.tv_sec - m_tmStart.tv_sec ) + ( ts.tv_nsec - m_tmStart.tv_nsec ) / 1.0E9;
47                 m_tmStart = ts;
48                 return dblRet;
49             }
50
51             double duration( native_duration_type dur )
52             {
53                 return double( dur ) / 1.0E9;
54             }
55
56             double duration()
57             {
58                 return duration( native_duration() );
59             }
60
61             native_duration_type    native_duration()
62             {
63                 native_timer_type ts;
64                 current( ts );
65                 return native_duration( m_tmStart, ts );
66             }
67
68             static native_duration_type    native_duration( const native_timer_type& nStart, const native_timer_type& nEnd )
69             {
70                 return native_duration_type( nEnd.tv_sec - nStart.tv_sec ) * 1000000000 + ( nEnd.tv_nsec - nStart.tv_nsec);
71             }
72
73             static unsigned long long random_seed()
74             {
75                 native_timer_type tmr;
76                 current( tmr );
77                 return ( ((unsigned long long)(tmr.tv_sec)) << 32 ) + tmr.tv_nsec;
78             }
79         };
80     }    // namespace posix
81
82 #ifndef CDS_CXX11_INLINE_NAMESPACE_SUPPORT
83     using posix::Timer;
84 #endif
85
86 }}    // namespace cds::OS
87 //@endcond
88
89 #endif // #ifndef __CDS_OS_POSIX_TIMER_H