timer.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (c) 2006-2018 Maxim Khizhinsky
  2. //
  3. // Distributed under the Boost Software License, Version 1.0. (See accompanying
  4. // file LICENSE or copy at http://www.boost.org/LICENSE_1_0.txt)
  5. #ifndef CDSLIB_OS_LINUX_TIMER_H
  6. #define CDSLIB_OS_LINUX_TIMER_H
  7. #ifndef CDSLIB_OS_TIMER_H
  8. # error "<cds/os/timer.h> must be included"
  9. #endif
  10. #include <time.h>
  11. //#include <sys/time.h>
  12. //@cond none
  13. namespace cds { namespace OS {
  14. inline namespace Linux {
  15. // High resolution timer
  16. class Timer {
  17. public:
  18. typedef struct timespec native_timer_type;
  19. typedef long long native_duration_type;
  20. private:
  21. native_timer_type m_tmStart;
  22. public:
  23. Timer() { current( m_tmStart ) ; }
  24. static void current( native_timer_type& tmr )
  25. {
  26. // faster than gettimeofday() and posix
  27. clock_gettime( CLOCK_REALTIME, &tmr );
  28. }
  29. static native_timer_type current()
  30. {
  31. native_timer_type tmr;
  32. current(tmr);
  33. return tmr;
  34. }
  35. double reset()
  36. {
  37. native_timer_type ts;
  38. current( ts );
  39. double dblRet = double( ( ts.tv_sec - m_tmStart.tv_sec ) + ( ts.tv_nsec - m_tmStart.tv_nsec )) / 1.0E9;
  40. m_tmStart = ts;
  41. return dblRet;
  42. }
  43. double duration( native_duration_type dur )
  44. {
  45. return double( dur ) / 1.0E9;
  46. }
  47. double duration()
  48. {
  49. return duration( native_duration());
  50. }
  51. native_duration_type native_duration()
  52. {
  53. native_timer_type ts;
  54. current( ts );
  55. return native_duration( m_tmStart, ts );
  56. }
  57. static native_duration_type native_duration( const native_timer_type& nStart, const native_timer_type& nEnd )
  58. {
  59. return native_duration_type( nEnd.tv_sec - nStart.tv_sec ) * 1000000000 + ( nEnd.tv_nsec - nStart.tv_nsec);
  60. }
  61. static unsigned long long random_seed()
  62. {
  63. native_timer_type tmr;
  64. current( tmr );
  65. return ( ((unsigned long long)(tmr.tv_sec)) << 32 ) + tmr.tv_nsec;
  66. }
  67. };
  68. } // namespace Linux
  69. }} // namespace cds::OS
  70. //@endcond
  71. #endif // #ifndef CDSLIB_OS_LINUX_TIMER_H