From bb9ac7b33541e87fd93fb1e62fb57eb27333e51b Mon Sep 17 00:00:00 2001 From: Bret Ambrose Date: Tue, 18 Feb 2025 09:36:28 -0800 Subject: [PATCH] Use sleep-aware monotonic clock if available --- cmake/AwsFeatureTests.cmake | 58 ++++++++++++++++++++++++++++++++++ include/aws/common/config.h.in | 1 + source/posix/clock.c | 4 ++- 3 files changed, 62 insertions(+), 1 deletion(-) diff --git a/cmake/AwsFeatureTests.cmake b/cmake/AwsFeatureTests.cmake index 813a3c9f8..132c3d217 100644 --- a/cmake/AwsFeatureTests.cmake +++ b/cmake/AwsFeatureTests.cmake @@ -131,6 +131,64 @@ if(MSVC) }" AWS_HAVE_MSVC_INTRINSICS_X64) endif() +if(NOT CMAKE_CROSSCOMPILING) + check_c_source_runs(" + #include + #include + + static const uint64_t NS_PER_SEC = 1000000000; + + bool get_time(uint64_t *current_time) { + struct timespec ts; + if (clock_gettime(CLOCK_BOOTTIME, &ts)) { + return false; + } + + uint64_t secs = (uint64_t)ts.tv_sec; + uint64_t n_secs = (uint64_t)ts.tv_nsec; + *current_time = (secs * NS_PER_SEC) + n_secs; + + return true; + } + + int main() { + uint64_t start_timestap = 0; + if (!get_time(&start_timestap)) { + return -1; + } + + return 0; + }" AWS_HAS_POSIX_BOOT_CLOCK) +else() + check_c_source_compiles(" + #include + #include + + static const uint64_t NS_PER_SEC = 1000000000; + + bool get_time(uint64_t *current_time) { + struct timespec ts; + if (clock_gettime(CLOCK_BOOTTIME, &ts)) { + return false; + } + + uint64_t secs = (uint64_t)ts.tv_sec; + uint64_t n_secs = (uint64_t)ts.tv_nsec; + *current_time = (secs * NS_PER_SEC) + n_secs; + + return true; + } + + int main() { + uint64_t start_timestap = 0; + if (!get_time(&start_timestap)) { + return -1; + } + + return 0; + }" AWS_HAS_POSIX_BOOT_CLOCK) +endif() + # This does a lot to detect when intrinsics are available and has to set cflags to do so. # leave it in its own file for ease of managing it. include(AwsSIMD) diff --git a/include/aws/common/config.h.in b/include/aws/common/config.h.in index 381d99c99..55a1e47cc 100644 --- a/include/aws/common/config.h.in +++ b/include/aws/common/config.h.in @@ -29,5 +29,6 @@ #cmakedefine AWS_ARCH_INTEL #cmakedefine AWS_ARCH_INTEL_X64 #cmakedefine AWS_USE_CPU_EXTENSIONS +#cmakedefine AWS_HAS_POSIX_BOOT_CLOCK #endif diff --git a/source/posix/clock.c b/source/posix/clock.c index 076f4d835..8a5874545 100644 --- a/source/posix/clock.c +++ b/source/posix/clock.c @@ -9,7 +9,9 @@ static const uint64_t NS_PER_SEC = 1000000000; -#if defined(CLOCK_MONOTONIC_RAW) +#if defined(AWS_HAS_POSIX_BOOT_CLOCK) +# define HIGH_RES_CLOCK CLOCK_BOOTTIME +#elif defined(CLOCK_MONOTONIC_RAW) # define HIGH_RES_CLOCK CLOCK_MONOTONIC_RAW #else # define HIGH_RES_CLOCK CLOCK_MONOTONIC