]> git.saurik.com Git - apple/libdispatch.git/blob - testing/dispatch_drift.c
libdispatch-84.5.5.tar.gz
[apple/libdispatch.git] / testing / dispatch_drift.c
1 #include <dispatch/dispatch.h>
2 #include <mach/mach_time.h>
3 #include <sys/time.h>
4 #include <unistd.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include "dispatch_test.h"
8
9 int
10 main(int argc __attribute__((unused)), char* argv[] __attribute__((unused)))
11 {
12 __block uint32_t count = 0;
13 __block uint64_t first_time_m = 0ULL;
14 __block double first_time_d;
15 __block double last_jitter = 0;
16 // 10 times a second
17 uint64_t interval = 1000000000 / 10;
18 double interval_d = interval / 1000000000.0;
19 // for 25 seconds
20 unsigned int target = 25 / interval_d;
21
22 test_start("Timer drift test");
23
24 dispatch_source_t t = dispatch_source_timer_create(DISPATCH_TIMER_INTERVAL, interval, 0, NULL, dispatch_get_main_queue(),
25 ^(dispatch_event_t event __attribute__((unused))) {
26 struct timeval now_tv;
27 static double first = 0;
28 gettimeofday(&now_tv, NULL);
29 double now = now_tv.tv_sec + now_tv.tv_usec / 1000000.0;
30
31 if (count == 0) {
32 // Because this is taken at 1st timer fire,
33 // later jitter values may be negitave.
34 // This doesn't effect the drift calculation.
35 first = now;
36 }
37 double goal = first + interval_d * count;
38 double jitter = goal - now;
39 double drift = jitter - last_jitter;
40
41 printf("%4d: jitter %f, drift %f\n", count, jitter, drift);
42 #if 0
43 test_double_less_than("drift", now_d - expected_fire_time_d, .001);
44 #endif
45
46 if (target <= ++count) {
47 if (drift < 0) {
48 drift = -drift;
49 }
50 test_double_less_than("drift", drift, 0.0001);
51 test_stop();
52 }
53 last_jitter = jitter;
54 });
55
56 test_ptr_notnull("timer source", t);
57
58 dispatch_main();
59 return 0;
60 }
61