1 #include "HalideRuntime.h"
2 
3 #ifndef __clockid_t_defined
4 #define __clockid_t_defined 1
5 
6 typedef int32_t clockid_t;
7 
8 #define CLOCK_REALTIME 0
9 #define CLOCK_MONOTONIC 1
10 #define CLOCK_PROCESS_CPUTIME_ID 2
11 #define CLOCK_THREAD_CPUTIME_ID 3
12 #define CLOCK_MONOTONIC_RAW 4
13 #define CLOCK_REALTIME_COARSE 5
14 #define CLOCK_MONOTONIC_COARSE 6
15 #define CLOCK_BOOTTIME 7
16 #define CLOCK_REALTIME_ALARM 8
17 #define CLOCK_BOOTTIME_ALARM 9
18 
19 #endif  // __clockid_t_defined
20 
21 #ifndef _STRUCT_TIMESPEC
22 #define _STRUCT_TIMESPEC
23 
24 struct timespec {
25     long tv_sec;  /* Seconds.  */
26     long tv_nsec; /* Nanoseconds.  */
27 };
28 
29 #endif  // _STRUCT_TIMESPEC
30 
31 extern "C" {
32 
33 WEAK bool halide_reference_clock_inited = false;
34 WEAK timespec halide_reference_clock;
35 
36 // The syscall number for gettime varies across platforms:
37 // -- android arm is 263
38 // -- i386 and android x86 is 265
39 // -- x64 is 228
40 
41 #ifndef SYS_CLOCK_GETTIME
42 
43 #ifdef BITS_64
44 #define SYS_CLOCK_GETTIME 228
45 #endif
46 
47 #ifdef BITS_32
48 #define SYS_CLOCK_GETTIME 265
49 #endif
50 
51 #endif
52 
53 extern int syscall(int num, ...);
54 
halide_start_clock(void * user_context)55 WEAK int halide_start_clock(void *user_context) {
56     // Guard against multiple calls
57     if (!halide_reference_clock_inited) {
58         syscall(SYS_CLOCK_GETTIME, CLOCK_REALTIME, &halide_reference_clock);
59         halide_reference_clock_inited = true;
60     }
61     return 0;
62 }
63 
halide_current_time_ns(void * user_context)64 WEAK int64_t halide_current_time_ns(void *user_context) {
65     timespec now;
66     // To avoid requiring people to link -lrt, we just make the syscall directly.
67 
68     syscall(SYS_CLOCK_GETTIME, CLOCK_REALTIME, &now);
69     int64_t d = int64_t(now.tv_sec - halide_reference_clock.tv_sec) * 1000000000;
70     int64_t nd = (now.tv_nsec - halide_reference_clock.tv_nsec);
71     return d + nd;
72 }
73 
74 extern int usleep(int);
halide_sleep_ms(void * user_context,int ms)75 WEAK void halide_sleep_ms(void *user_context, int ms) {
76     usleep(ms * 1000);
77 }
78 }
79