fork download
  1. #ifndef CLOCK_TIMESPEC_H
  2. #define CLOCK_TIMESPEC_H
  3.  
  4.  
  5. #include <time.h>
  6.  
  7. #include <cassert>
  8. #include <stdexcept>
  9. #include <iostream>
  10.  
  11. namespace clock {
  12.  
  13. typedef timespec ts;
  14.  
  15. static clockid_t const clock_source = CLOCK_REALTIME;
  16.  
  17. ts now()
  18. {
  19. ts t;
  20. int const res = clock_gettime(clock_source, &t);
  21. if (res)
  22. throw std::runtime_error("timing::now failed");
  23. return t;
  24. }
  25.  
  26. ts minute(unsigned int m)
  27. {
  28. ts t = {0, 0};
  29. t.tv_sec = 60 * m;
  30. return t;
  31. }
  32.  
  33. ts second(unsigned int s)
  34. {
  35. ts t = {0, 0};
  36. t.tv_sec = s;
  37. return t;
  38. }
  39.  
  40. ts millisecond(unsigned int ms)
  41. {
  42. ts t = {0, 0};
  43. t.tv_nsec = 1000000 * ms;
  44. return t;
  45. }
  46.  
  47. ts microsecond(unsigned int us)
  48. {
  49. ts t = {0, 0};
  50. t.tv_nsec = 1000 * us;
  51. return t;
  52. }
  53.  
  54. ts nanosecond(unsigned int ns)
  55. {
  56. ts t = {0, 0};
  57. t.tv_nsec = ns;
  58. return t;
  59. }
  60.  
  61. ts operator+(ts const& a, ts const& b)
  62. {
  63. ts t = {0, 0};
  64. // tv_nsec<1*10^9 => a.tv_nsec+b.tv_nsec < 2*10^9 < max(31 bit)
  65. t.tv_nsec = a.tv_nsec + b.tv_nsec;
  66. if (t.tv_nsec >= 1000000000)
  67. {
  68. t.tv_sec = 1;
  69. t.tv_nsec -= 1000000000;
  70. }
  71. t.tv_sec += a.tv_sec + b.tv_sec;
  72. return t;
  73. }
  74.  
  75.  
  76. }
  77.  
  78. #endif
Not running #stdin #stdout 0s 0KB
stdin
Standard input is empty
stdout
Standard output is empty