| 1 |
// Copyright (c) Microsoft. All rights reserved. |
| 2 |
// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 3 |
|
| 4 |
#include <stdlib.h> |
| 5 |
#include "azure_c_shared_utility/xlogging.h" |
| 6 |
#include "linux_time.h" |
| 7 |
|
| 8 |
#ifdef __MACH__ |
| 9 |
#include <mach/clock.h> |
| 10 |
#include <mach/mach.h> |
| 11 |
#endif |
| 12 |
|
| 13 |
|
| 14 |
#ifndef __MACH__ |
| 15 |
clockid_t time_basis = -1; |
| 16 |
#endif |
| 17 |
|
| 18 |
void set_time_basis(void) |
| 19 |
{ |
| 20 |
// The time basis depends on what clock is available. Prefer CLOCK_MONOTONIC, |
| 21 |
// then CLOCK_REALTIME, otherwise query the default pthread_condattr_t value |
| 22 |
// and use that. Note the time basis stuff requires _POSIX_TIMERS [TMR] at a |
| 23 |
// minimum; querying pthread_condattr_t requires _POSIX_CLOCK_SELECTION [CS]. |
| 24 |
// OSX has neither so we use a platform-specific clock. |
| 25 |
#ifndef __MACH__ |
| 26 |
#if defined(CLOCK_MONOTONIC) |
| 27 |
time_basis = CLOCK_MONOTONIC; |
| 28 |
#elif defined(CLOCK_REALTIME) |
| 29 |
time_basis = CLOCK_REALTIME; |
| 30 |
#else |
| 31 |
pthread_condattr_t cattr; |
| 32 |
pthread_condattr_init(&cattr); |
| 33 |
pthread_condattr_getclock(&cattr, &time_basis); |
| 34 |
pthread_condattr_destroy(&cattr); |
| 35 |
#endif |
| 36 |
#endif |
| 37 |
} |
| 38 |
|
| 39 |
int get_time_ns(struct timespec* ts) |
| 40 |
{ |
| 41 |
int err; |
| 42 |
|
| 43 |
#ifdef __MACH__ |
| 44 |
clock_serv_t cclock; |
| 45 |
mach_timespec_t mts; |
| 46 |
err = host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock); |
| 47 |
if (!err) |
| 48 |
{ |
| 49 |
err = clock_get_time(cclock, &mts); |
| 50 |
mach_port_deallocate(mach_task_self(), cclock); |
| 51 |
|
| 52 |
if (!err) |
| 53 |
{ |
| 54 |
ts->tv_sec = mts.tv_sec; |
| 55 |
ts->tv_nsec = mts.tv_nsec; |
| 56 |
} |
| 57 |
} |
| 58 |
#else |
| 59 |
err = clock_gettime(time_basis, ts); |
| 60 |
#endif |
| 61 |
return err; |
| 62 |
} |
| 63 |
|
| 64 |
int64_t get_time_ms(void) |
| 65 |
{ |
| 66 |
struct timespec ts; |
| 67 |
if (get_time_ns(&ts) != 0) |
| 68 |
{ |
| 69 |
LogError("Failed to get the current time"); |
| 70 |
return INVALID_TIME_VALUE; |
| 71 |
} |
| 72 |
|
| 73 |
return (int64_t)((int64_t)ts.tv_sec * MILLISECONDS_IN_1_SECOND + (int64_t)ts.tv_nsec / NANOSECONDS_IN_1_MILLISECOND); |
| 74 |
} |
| 75 |
|