xref: /xnu-11417.121.6/tests/mach_get_times.c (revision a1e26a70f38d1d7daa7b49b258e2f8538ad81650)
1 #include <stdlib.h>
2 #include <time.h>
3 #include <sys/time.h>
4 #include <mach/mach_time.h>
5 
6 #include <darwintest.h>
7 #include <darwintest_utils.h>
8 
9 T_GLOBAL_META(T_META_RUN_CONCURRENTLY(true));
10 
11 #define T_LOG_VERBOSE(...)
12 
13 #define timespec2nanosec(ts) ((uint64_t)((ts)->tv_sec) * NSEC_PER_SEC + (uint64_t)((ts)->tv_nsec))
14 
15 T_DECL(mach_get_times, "mach_get_times()",
16     T_META_CHECK_LEAKS(false), T_META_ALL_VALID_ARCHS(true))
17 {
18 	const int ITERATIONS = 500000 * dt_ncpu();
19 	struct timespec gtod_ts;
20 
21 	uint64_t last_absolute, last_continuous, last_gtod;
22 	T_QUIET; T_ASSERT_EQ(mach_get_times(&last_absolute, &last_continuous, &gtod_ts), KERN_SUCCESS, NULL);
23 	last_gtod = timespec2nanosec(&gtod_ts);
24 
25 	for (int i = 0; i < ITERATIONS; i++) {
26 		uint64_t absolute, continuous, gtod;
27 		T_QUIET; T_ASSERT_EQ(mach_get_times(&absolute, &continuous, &gtod_ts), KERN_SUCCESS, NULL);
28 		gtod = timespec2nanosec(&gtod_ts);
29 
30 		T_LOG_VERBOSE("[%d] abs: %llu.%09llu(+%llu)\tcont: %llu.%09llu(+%llu)\tgtod:%llu.%09llu(+%llu)", i,
31 		    absolute / NSEC_PER_SEC, absolute % NSEC_PER_SEC, absolute - last_absolute,
32 		    continuous / NSEC_PER_SEC, continuous % NSEC_PER_SEC, continuous - last_continuous,
33 		    gtod / NSEC_PER_SEC, gtod % NSEC_PER_SEC, gtod - last_gtod);
34 
35 		T_QUIET; T_EXPECT_EQ(absolute - last_absolute, continuous - last_continuous, NULL);
36 
37 		int64_t gtod_diff = (int64_t)gtod - (int64_t)last_gtod;
38 		T_QUIET; T_ASSERT_LE((uint64_t)llabs(gtod_diff), NSEC_PER_SEC, NULL);
39 
40 		last_absolute = absolute;
41 		last_continuous = continuous;
42 		last_gtod = gtod;
43 
44 		gtod_ts.tv_sec = 0; gtod_ts.tv_nsec = 0;
45 	}
46 }
47