From 001dc3f33d752c3131e5f8e6d63f29871356d20a Mon Sep 17 00:00:00 2001 From: James Hilliard Date: Wed, 13 Oct 2021 16:54:24 -0600 Subject: [PATCH] util: Actually return uptime on OSX/Linux for mg_millis The documentation for mg_millis indicates it will: Return current uptime in milliseconds. So we should use API's that actually return uptime. Signed-off-by: James Hilliard --- mongoose.c | 19 +++++++++++++++++++ src/util.c | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/mongoose.c b/mongoose.c index 9411a8a9..cc5272a9 100644 --- a/mongoose.c +++ b/mongoose.c @@ -4153,6 +4153,10 @@ struct mg_str mg_url_pass(const char *url) { +#if MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__) +#include +#endif + char *mg_file_read(const char *path, size_t *sizep) { FILE *fp; char *data = NULL; @@ -4498,9 +4502,24 @@ unsigned long mg_millis(void) { return xTaskGetTickCount() * portTICK_PERIOD_MS; #elif MG_ARCH == MG_ARCH_AZURERTOS return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND); +#elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__) + uint64_t ticks = mach_absolute_time(); + static mach_timebase_info_data_t timebase; + mach_timebase_info(&timebase); + double ticks_to_nanos = (double)timebase.numer / timebase.denom; + uint64_t uptime_nanos = (uint64_t)(ticks_to_nanos * ticks); + return (unsigned long) (uptime_nanos / 1000000); #else struct timespec ts; +#ifdef _POSIX_MONOTONIC_CLOCK +#ifdef CLOCK_MONOTONIC_RAW + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); +#else + clock_gettime(CLOCK_MONOTONIC, &ts); +#endif +#else clock_gettime(CLOCK_REALTIME, &ts); +#endif return (unsigned long) ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000); #endif diff --git a/src/util.c b/src/util.c index 97ab47c8..9eb8f615 100644 --- a/src/util.c +++ b/src/util.c @@ -2,6 +2,10 @@ #include "util.h" +#if MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__) +#include +#endif + char *mg_file_read(const char *path, size_t *sizep) { FILE *fp; char *data = NULL; @@ -347,9 +351,24 @@ unsigned long mg_millis(void) { return xTaskGetTickCount() * portTICK_PERIOD_MS; #elif MG_ARCH == MG_ARCH_AZURERTOS return tx_time_get() * (1000 /* MS per SEC */ / TX_TIMER_TICKS_PER_SECOND); +#elif MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__) + uint64_t ticks = mach_absolute_time(); + static mach_timebase_info_data_t timebase; + mach_timebase_info(&timebase); + double ticks_to_nanos = (double)timebase.numer / timebase.denom; + uint64_t uptime_nanos = (uint64_t)(ticks_to_nanos * ticks); + return (unsigned long) (uptime_nanos / 1000000); #else struct timespec ts; +#ifdef _POSIX_MONOTONIC_CLOCK +#ifdef CLOCK_MONOTONIC_RAW + clock_gettime(CLOCK_MONOTONIC_RAW, &ts); +#else + clock_gettime(CLOCK_MONOTONIC, &ts); +#endif +#else clock_gettime(CLOCK_REALTIME, &ts); +#endif return (unsigned long) ((uint64_t) ts.tv_sec * 1000 + (uint64_t) ts.tv_nsec / 1000000); #endif