Skip to content

Commit ea9fa93

Browse files
authored
Merge pull request #52 from status-im/osxclock
Fix clock_gettime() is not available on old MacOS.
2 parents 7029f8b + a039011 commit ea9fa93

File tree

2 files changed

+24
-10
lines changed

2 files changed

+24
-10
lines changed

chronos.nimble

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
packageName = "chronos"
2-
version = "2.2.9"
2+
version = "2.3.0"
33
author = "Status Research & Development GmbH"
44
description = "Chronos"
55
license = "Apache License 2.0 or MIT"

chronos/timer.nim

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -101,22 +101,36 @@ elif defined(macosx):
101101
result = (cast[uint64](t.tv_sec) * 1_000_000_000 +
102102
cast[uint64](t.tv_usec) * 1_000)
103103
else:
104-
from posix import clock_gettime, Timespec, CLOCK_MONOTONIC
104+
type
105+
MachTimebaseInfo {.importc: "struct mach_timebase_info",
106+
header: "<mach/mach_time.h>", pure, final.} = object
107+
numer: uint32
108+
denom: uint32
109+
110+
proc mach_timebase_info(info: var MachTimebaseInfo) {.importc,
111+
header: "<mach/mach_time.h>".}
112+
proc mach_absolute_time(): uint64 {.importc, header: "<mach/mach_time.h>".}
113+
114+
var queryFrequencyN: uint64
115+
var queryFrequencyD: uint64
116+
117+
proc setupQueryFrequence() =
118+
var info: MachTimebaseInfo
119+
mach_timebase_info(info)
120+
queryFrequencyN = info.numer
121+
queryFrequencyD = info.denom
105122

106123
proc fastEpochTime*(): uint64 {.
107124
inline, deprecated: "Use Moment.now()".} =
108125
## Procedure's resolution is millisecond.
109-
var t: Timespec
110-
discard clock_gettime(CLOCK_MONOTONIC, t)
111-
result = ((cast[uint64](t.tv_sec) * 1_000) +
112-
(cast[uint64](t.tv_nsec) div 1_000_000))
126+
result = (mach_absolute_time() * queryFrequencyN) div queryFrequencyD
127+
result = result div 1_000_000
113128

114129
proc fastEpochTimeNano(): uint64 {.inline.} =
115130
## Procedure's resolution is nanosecond.
116-
var t: Timespec
117-
discard clock_gettime(CLOCK_MONOTONIC, t)
118-
result = cast[uint64](t.tv_sec) * 1_000_000_000'u64 +
119-
cast[uint64](t.tv_nsec)
131+
result = (mach_absolute_time() * queryFrequencyN) div queryFrequencyD
132+
133+
setupQueryFrequence()
120134

121135
elif defined(posix):
122136
from posix import clock_gettime, Timespec, CLOCK_REALTIME, CLOCK_MONOTONIC

0 commit comments

Comments
 (0)