Merge pull request #1380 from jameshilliard/fix-time

util: Actually return uptime on OSX/Linux for mg_millis
This commit is contained in:
Sergey Lyubka 2021-10-22 14:06:44 +01:00 committed by GitHub
commit 126d556d6a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 38 additions and 0 deletions

View File

@ -4162,6 +4162,10 @@ struct mg_str mg_url_pass(const char *url) {
#if MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
#include <mach/mach_time.h>
#endif
char *mg_file_read(const char *path, size_t *sizep) {
FILE *fp;
char *data = NULL;
@ -4507,9 +4511,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

View File

@ -2,6 +2,10 @@
#include "util.h"
#if MG_ARCH == MG_ARCH_UNIX && defined(__APPLE__)
#include <mach/mach_time.h>
#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