monotimes.nim 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. #
  2. #
  3. # Nim's Runtime Library
  4. # (c) Copyright 2019 Nim contributors
  5. #
  6. # See the file "copying.txt", included in this
  7. # distribution, for details about the copyright.
  8. #
  9. ##[
  10. The ``std/monotimes`` module implements monotonic timestamps. A monotonic
  11. timestamp represents the time that has passed since some system defined
  12. point in time. The monotonic timestamps are guaranteed to always increase,
  13. meaning that that the following is guaranteed to work:
  14. .. code-block:: nim
  15. let a = getMonoTime()
  16. # ... do some work
  17. let b = getMonoTime()
  18. assert a <= b
  19. This is not guaranteed for the `times.Time` type! This means that the
  20. `MonoTime` should be used when measuring durations of time with
  21. high precision.
  22. However, since `MonoTime` represents the time that has passed since some
  23. unknown time origin, it cannot be converted to a human readable timestamp.
  24. If this is required, the `times.Time` type should be used instead.
  25. The `MonoTime` type stores the timestamp in nanosecond resolution, but note
  26. that the actual supported time resolution differs for different systems.
  27. See also
  28. ========
  29. * `times module <times.html>`_
  30. ]##
  31. import times
  32. type
  33. MonoTime* = object ## Represents a monotonic timestamp.
  34. ticks: int64
  35. when defined(macosx):
  36. type
  37. MachTimebaseInfoData {.pure, final, importc: "mach_timebase_info_data_t",
  38. header: "<mach/mach_time.h>".} = object
  39. numer, denom: int32
  40. proc mach_absolute_time(): int64 {.importc, header: "<mach/mach.h>".}
  41. proc mach_timebase_info(info: var MachTimebaseInfoData) {.importc,
  42. header: "<mach/mach_time.h>".}
  43. when defined(js):
  44. proc getJsTicks: float =
  45. ## Returns ticks in the unit seconds
  46. {.emit: """
  47. var isNode = typeof module !== 'undefined' && module.exports
  48. if (isNode) {
  49. var process = require('process');
  50. var time = process.hrtime()
  51. return time[0] + time[1] / 1000000000;
  52. } else {
  53. return window.performance.now() / 1000;
  54. }
  55. """.}
  56. # Workaround for #6752.
  57. {.push overflowChecks: off.}
  58. proc `-`(a, b: int64): int64 =
  59. system.`-`(a, b)
  60. proc `+`(a, b: int64): int64 =
  61. system.`+`(a, b)
  62. {.pop.}
  63. elif defined(posix):
  64. import posix
  65. elif defined(windows):
  66. proc QueryPerformanceCounter(res: var uint64) {.
  67. importc: "QueryPerformanceCounter", stdcall, dynlib: "kernel32".}
  68. proc QueryPerformanceFrequency(res: var uint64) {.
  69. importc: "QueryPerformanceFrequency", stdcall, dynlib: "kernel32".}
  70. proc getMonoTime*(): MonoTime {.tags: [TimeEffect].} =
  71. ## Get the current `MonoTime` timestamp.
  72. ##
  73. ## When compiled with the JS backend and executed in a browser,
  74. ## this proc calls `window.performance.now()`, which is not supported by
  75. ## older browsers. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now)
  76. ## for more information.
  77. when defined(js):
  78. let ticks = getJsTicks()
  79. result = MonoTime(ticks: (ticks * 1_000_000_000).int64)
  80. elif defined(macosx):
  81. let ticks = mach_absolute_time()
  82. var machAbsoluteTimeFreq: MachTimebaseInfoData
  83. mach_timebase_info(machAbsoluteTimeFreq)
  84. result = MonoTime(ticks: ticks * machAbsoluteTimeFreq.numer div
  85. machAbsoluteTimeFreq.denom)
  86. elif defined(posix):
  87. var ts: Timespec
  88. discard clock_gettime(CLOCK_MONOTONIC, ts)
  89. result = MonoTime(ticks: ts.tv_sec.int64 * 1_000_000_000 +
  90. ts.tv_nsec.int64)
  91. elif defined(windows):
  92. var ticks: uint64
  93. QueryPerformanceCounter(ticks)
  94. var freq: uint64
  95. QueryPerformanceFrequency(freq)
  96. let queryPerformanceCounterFreq = 1_000_000_000'u64 div freq
  97. result = MonoTime(ticks: (ticks * queryPerformanceCounterFreq).int64)
  98. proc ticks*(t: MonoTime): int64 =
  99. ## Returns the raw ticks value from a `MonoTime`. This value always uses
  100. ## nanosecond time resolution.
  101. t.ticks
  102. proc `$`*(t: MonoTime): string =
  103. $t.ticks
  104. proc `-`*(a, b: MonoTime): Duration =
  105. ## Returns the difference between two `MonoTime` timestamps as a `Duration`.
  106. initDuration(nanoseconds = (a.ticks - b.ticks))
  107. proc `+`*(a: MonoTime, b: Duration): MonoTime =
  108. ## Increases `a` by `b`.
  109. MonoTime(ticks: a.ticks + b.inNanoseconds)
  110. proc `-`*(a: MonoTime, b: Duration): MonoTime =
  111. ## Reduces `a` by `b`.
  112. MonoTime(ticks: a.ticks - b.inNanoseconds)
  113. proc `<`*(a, b: MonoTime): bool =
  114. ## Returns true if `a` happened before `b`.
  115. a.ticks < b.ticks
  116. proc `<=`*(a, b: MonoTime): bool =
  117. ## Returns true if `a` happened before `b` or if they happened simultaneous.
  118. a.ticks <= b.ticks
  119. proc `==`*(a, b: MonoTime): bool =
  120. ## Returns true if `a` and `b` happened simultaneous.
  121. a.ticks == b.ticks
  122. proc high*(typ: typedesc[MonoTime]): MonoTime =
  123. ## Returns the highest representable `MonoTime`.
  124. MonoTime(ticks: high(int64))
  125. proc low*(typ: typedesc[MonoTime]): MonoTime =
  126. ## Returns the lowest representable `MonoTime`.
  127. MonoTime(ticks: low(int64))
  128. when isMainModule:
  129. let d = initDuration(nanoseconds = 10)
  130. let t1 = getMonoTime()
  131. let t2 = t1 + d
  132. doAssert t2 - t1 == d
  133. doAssert t1 == t1
  134. doAssert t1 != t2
  135. doAssert t2 - d == t1
  136. doAssert t1 < t2
  137. doAssert t1 <= t2
  138. doAssert t1 <= t1
  139. doAssert not(t2 < t1)
  140. doAssert t1 < high(MonoTime)
  141. doAssert low(MonoTime) < t1