Improve clock_gettime usage

- correctly use value of _POSIX_MONOTONIC_CLOCK
- drop special path for macOS: it supports clock_gettime since macOS 10.12
This commit is contained in:
sfan5 2023-12-12 13:28:07 +01:00
parent d4123a387c
commit bd06466d3a
1 changed files with 7 additions and 17 deletions

View File

@ -89,11 +89,6 @@ with this program; if not, write to the Free Software Foundation, Inc.,
#ifndef _WIN32 // POSIX
#include <sys/time.h>
#include <ctime>
#if defined(__MACH__) && defined(__APPLE__)
#include <mach/clock.h>
#include <mach/mach.h>
#endif
#endif
namespace porting
@ -183,21 +178,16 @@ inline u64 getTimeNs() { return os_get_time(1000*1000*1000); }
inline void os_get_clock(struct timespec *ts)
{
#if defined(__MACH__) && defined(__APPLE__)
// From http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x
// OS X does not have clock_gettime, use clock_get_time
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts->tv_sec = mts.tv_sec;
ts->tv_nsec = mts.tv_nsec;
#elif defined(CLOCK_MONOTONIC_RAW)
#if defined(CLOCK_MONOTONIC_RAW)
clock_gettime(CLOCK_MONOTONIC_RAW, ts);
#elif defined(_POSIX_MONOTONIC_CLOCK)
#elif defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK > 0
clock_gettime(CLOCK_MONOTONIC, ts);
#else
# if defined(_POSIX_MONOTONIC_CLOCK) && _POSIX_MONOTONIC_CLOCK == 0
// zero means it might be supported at runtime
if (clock_gettime(CLOCK_MONOTONIC, ts) == 0)
return;
# endif
struct timeval tv;
gettimeofday(&tv, NULL);
TIMEVAL_TO_TIMESPEC(&tv, ts);