680098c8de809c75cdc0857d82d525ffa37ecadf
[cvc5.git] / src / lib / clock_gettime.c
1 /********************* */
2 /*! \file clock_gettime.c
3 ** \verbatim
4 ** Top contributors (to current version):
5 ** Morgan Deters, Tim King, Paul Meng
6 ** This file is part of the CVC4 project.
7 ** Copyright (c) 2009-2018 by the authors listed in the file AUTHORS
8 ** in the top-level source directory) and their institutional affiliations.
9 ** All rights reserved. See the file COPYING in the top-level source
10 ** directory for licensing information.\endverbatim
11 **
12 ** \brief Replacement for clock_gettime() for systems without it (like
13 ** Mac OS X)
14 **
15 ** Replacement for clock_gettime() for systems without it (like Mac
16 ** OS X).
17 **/
18
19 // #warning "TODO(taking): Make lib/clock_gettime.h cvc4_private.h again."
20
21 #include "lib/clock_gettime.h"
22
23 #ifdef __cplusplus
24 extern "C" {
25 #endif /* __cplusplus */
26
27 #ifdef __APPLE__
28
29 #include <stdio.h>
30 #include <errno.h>
31 #include <mach/mach_time.h>
32
33 static double s_clockconv = 0.0;
34
35 long clock_gettime(clockid_t which_clock, struct timespec* tp) {
36 if( s_clockconv == 0.0 ) {
37 mach_timebase_info_data_t tb;
38 kern_return_t err = mach_timebase_info(&tb);
39 if(err == 0) {
40 s_clockconv = ((double) tb.numer) / tb.denom;
41 } else {
42 return -EINVAL;
43 }
44 }
45
46 switch(which_clock) {
47 case CLOCK_REALTIME:
48 case CLOCK_REALTIME_HR:
49 case CLOCK_MONOTONIC:
50 case CLOCK_MONOTONIC_HR: {
51 uint64_t t = mach_absolute_time() * s_clockconv;
52 tp->tv_sec = t / 1000000000ul;
53 tp->tv_nsec = t % 1000000000ul;
54 }
55 break;
56 default:
57 return -EINVAL;
58 }
59
60 return 0;
61 }
62
63 #else /* not defined __APPLE__ */
64 #ifdef __WIN32__
65
66 #include <time.h>
67 #include <windows.h>
68
69 long clock_gettime(clockid_t which_clock, struct timespec* tp) {
70 if(tp != NULL) {
71 FILETIME ft;
72 GetSystemTimeAsFileTime(&ft);
73 uint64_t nanos = ((((uint64_t)ft.dwHighDateTime) << 32) | ft.dwLowDateTime) * 100;
74 tp->tv_sec = nanos / 1000000000ul;
75 tp->tv_nsec = nanos % 1000000000ul;
76 }
77 return 0;
78 }
79
80 #endif /* closing #ifdef __WIN32__ */
81 #endif /* closing #else for #ifdef __APPLE__ / __WIN32__ */
82
83 #ifdef __cplusplus
84 }/* extern "C" */
85 #endif /* __cplusplus */