Skip to content

Commit e245cbe

Browse files
authored
Merge pull request swiftlang#320 from apple/jblache/clock_monotonic
Base approximate time on a monotonic clock, like absolute time
2 parents 3b06f54 + 58b23b8 commit e245cbe

File tree

2 files changed

+17
-4
lines changed

2 files changed

+17
-4
lines changed

configure.ac

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,7 @@ AC_CHECK_FUNCS([mach_port_construct])
399399
#
400400
# Find functions and declarations we care about.
401401
#
402-
AC_CHECK_DECLS([CLOCK_UPTIME, CLOCK_MONOTONIC, CLOCK_REALTIME, CLOCK_UPTIME_FAST], [], [],
402+
AC_CHECK_DECLS([CLOCK_UPTIME, CLOCK_MONOTONIC, CLOCK_REALTIME, CLOCK_UPTIME_FAST, CLOCK_MONOTONIC_COARSE], [], [],
403403
[[#include <time.h>]])
404404
AC_CHECK_DECLS([NOTE_NONE, NOTE_REAP, NOTE_REVOKE, NOTE_SIGNAL, NOTE_LOWAT], [], [],
405405
[[#include <sys/event.h>]])

src/shims/time.h

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,19 @@ _dispatch_get_nanoseconds(void)
121121
#endif
122122
}
123123

124+
/* On the use of clock sources in the CLOCK_MONOTONIC family
125+
*
126+
* The code below requires monotonic clock sources that only tick
127+
* while the machine is running.
128+
*
129+
* Per POSIX, the CLOCK_MONOTONIC family is supposed to tick during
130+
* machine sleep; this is not the case on Linux, and that behavior
131+
* became part of the Linux ABI.
132+
*
133+
* Using the CLOCK_MONOTONIC family on POSIX-compliant platforms
134+
* will lead to bugs, hence its use is restricted to Linux.
135+
*/
136+
124137
static inline uint64_t
125138
_dispatch_absolute_time(void)
126139
{
@@ -130,7 +143,7 @@ _dispatch_absolute_time(void)
130143
struct timespec ts;
131144
dispatch_assume_zero(clock_gettime(CLOCK_UPTIME, &ts));
132145
return _dispatch_timespec_to_nano(ts);
133-
#elif HAVE_DECL_CLOCK_MONOTONIC
146+
#elif HAVE_DECL_CLOCK_MONOTONIC && defined(__linux__)
134147
struct timespec ts;
135148
dispatch_assume_zero(clock_gettime(CLOCK_MONOTONIC, &ts));
136149
return _dispatch_timespec_to_nano(ts);
@@ -152,9 +165,9 @@ _dispatch_approximate_time(void)
152165
struct timespec ts;
153166
dispatch_assume_zero(clock_gettime(CLOCK_UPTIME_FAST, &ts));
154167
return _dispatch_timespec_to_nano(ts);
155-
#elif defined(__linux__)
168+
#elif HAVE_DECL_CLOCK_MONOTONIC_COARSE && defined(__linux__)
156169
struct timespec ts;
157-
dispatch_assume_zero(clock_gettime(CLOCK_REALTIME_COARSE, &ts));
170+
dispatch_assume_zero(clock_gettime(CLOCK_MONOTONIC_COARSE, &ts));
158171
return _dispatch_timespec_to_nano(ts);
159172
#else
160173
return _dispatch_absolute_time();

0 commit comments

Comments
 (0)