Skip to content

zend_hrtime: Check posix clock once and prefer CLOCK_MONOTONIC_RAW #19221

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions Zend/zend_hrtime.c
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,8 @@
# include <time.h>
# include <string.h>

ZEND_API clockid_t zend_hrtime_posix_clock_id = CLOCK_MONOTONIC;

#elif ZEND_HRTIME_PLATFORM_WINDOWS

# define WIN32_LEAN_AND_MEAN
Expand Down Expand Up @@ -66,5 +68,24 @@ void zend_startup_hrtime(void)

mach_timebase_info(&zend_hrtime_timerlib_info);

#elif ZEND_HRTIME_PLATFORM_POSIX

struct timespec ts;

#ifdef CLOCK_MONOTONIC_RAW
if (EXPECTED(0 == clock_gettime(CLOCK_MONOTONIC_RAW, &ts))) {
zend_hrtime_posix_clock_id = CLOCK_MONOTONIC_RAW;
return;
}
#endif

if (EXPECTED(0 == clock_gettime(zend_hrtime_posix_clock_id, &ts))) {
return;
}

// zend_error mechanism is not initialized at that point
fprintf(stderr, "No working CLOCK_MONOTONIC* found, this should never happen\n");
abort();

#endif
}
10 changes: 6 additions & 4 deletions Zend/zend_hrtime.h
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,10 @@ ZEND_API extern double zend_hrtime_timer_scale;
# include <string.h>
ZEND_API extern mach_timebase_info_data_t zend_hrtime_timerlib_info;

#elif ZEND_HRTIME_PLATFORM_POSIX

ZEND_API extern clockid_t zend_hrtime_posix_clock_id;

#endif

#define ZEND_NANO_IN_SEC UINT64_C(1000000000)
Expand All @@ -92,10 +96,8 @@ static zend_always_inline zend_hrtime_t zend_hrtime(void)
return (zend_hrtime_t)mach_absolute_time() * zend_hrtime_timerlib_info.numer / zend_hrtime_timerlib_info.denom;
#elif ZEND_HRTIME_PLATFORM_POSIX
struct timespec ts = { .tv_sec = 0, .tv_nsec = 0 };
if (EXPECTED(0 == clock_gettime(CLOCK_MONOTONIC, &ts))) {
return ((zend_hrtime_t) ts.tv_sec * (zend_hrtime_t)ZEND_NANO_IN_SEC) + ts.tv_nsec;
}
return 0;
clock_gettime(zend_hrtime_posix_clock_id, &ts);
return ((zend_hrtime_t) ts.tv_sec * (zend_hrtime_t)ZEND_NANO_IN_SEC) + ts.tv_nsec;
#elif ZEND_HRTIME_PLATFORM_HPUX
return (zend_hrtime_t) gethrtime();
#elif ZEND_HRTIME_PLATFORM_AIX
Expand Down
Loading