682269458904012c8f9d2d2ebc0604ad304e95ec
[cvc5.git] / src / lib / clock_gettime.c
1 /********************* */
2 /*! \file clock_gettime.c
3 ** \verbatim
4 ** Original author:
5 ** Major contributors: none
6 ** Minor contributors (to current version): none
7 ** This file is part of the CVC4 prototype.
8 ** Copyright (c) 2009, 2010 The Analysis of Computer Systems Group (ACSys)
9 ** Courant Institute of Mathematical Sciences
10 ** New York University
11 ** See the file COPYING in the top-level source directory for licensing
12 ** information.\endverbatim
13 **
14 ** \brief Replacement for clock_gettime() for systems without it (like
15 ** Mac OS X)
16 **
17 ** Replacement for clock_gettime() for systems without it (like Mac
18 ** OS X).
19 **/
20
21 #include <stdio.h>
22 #include <errno.h>
23 #include <time.h>
24
25 #include "lib/clock_gettime.h"
26
27 #ifdef __cplusplus
28 extern "C" {
29 #endif /* __cplusplus */
30
31 #ifndef __APPLE__
32 # warning This code assumes you're on Mac OS X, and you don't seem to be. You'll likely have problems.
33 #endif /* __APPLE__ */
34
35 #include <mach/mach_time.h>
36
37 static double s_clockconv = 0.0;
38
39 long clock_gettime(clockid_t which_clock, struct timespec *tp) {
40 if( s_clockconv == 0.0 ) {
41 mach_timebase_info_data_t tb;
42 kern_return_t err = mach_timebase_info(&tb);
43 if(err == 0) {
44 s_clockconv = ((double) tb.numer) / tb.denom;
45 } else {
46 return -EINVAL;
47 }
48 }
49
50 switch(which_clock) {
51 case CLOCK_REALTIME:
52 case CLOCK_REALTIME_HR:
53 case CLOCK_MONOTONIC:
54 case CLOCK_MONOTONIC_HR: {
55 uint64_t t = mach_absolute_time() * s_clockconv;
56 tp->tv_sec = t / 1000000000ul;
57 tp->tv_nsec = t % 1000000000ul;
58 }
59 break;
60 default:
61 return -EINVAL;
62 }
63
64 return 0;
65 }
66
67 #ifdef __cplusplus
68 }/* extern "C" */
69 #endif /* __cplusplus */