]> git.saurik.com Git - apple/libdispatch.git/blob - testing/float_parsing.c
libdispatch-84.5.3.tar.gz
[apple/libdispatch.git] / testing / float_parsing.c
1 #include <dispatch/dispatch.h>
2 #include <sys/types.h>
3 #include <sys/param.h>
4 #include <sys/mman.h>
5 #include <sys/stat.h>
6 #include <fcntl.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #include <unistd.h>
10 #include <assert.h>
11 #include <string.h>
12 #include <math.h>
13
14 #define MAXLAPS (512 * 1024)
15
16 static void
17 test(size_t LAPS, char *nums)
18 {
19 uint64_t concurrent_cycles;
20 uint64_t serial_cycles;
21 char **result_strings;
22 char *nums_off;
23 double *results;
24 size_t i;
25
26 result_strings = calloc(1, sizeof(char *) * LAPS);
27 assert(result_strings);
28
29 results = calloc(1, sizeof(double) * LAPS);
30 assert(results);
31
32 printf("%zu random floats\n", LAPS);
33
34 i = 0;
35 nums_off = nums;
36 do {
37 result_strings[i] = nums_off;
38 do {
39 nums_off++;
40 assert(*nums_off);
41 } while (*nums_off != '\n');
42 i++;
43 nums_off++;
44 } while (i < LAPS);
45
46 for (i = 0; i < LAPS; i++) {
47 assert(result_strings[i]);
48 }
49
50 concurrent_cycles = dispatch_benchmark(10, ^{
51 dispatch_apply(LAPS, dispatch_get_concurrent_queue(0), ^(size_t idx) {
52 results[idx] = strtod(result_strings[idx], NULL);
53 });
54 });
55
56 for (i = 0; i < LAPS; i++) {
57 assert(results[i]);
58 }
59
60 serial_cycles = dispatch_benchmark(10, ^{
61 size_t k = 0;
62 do {
63 results[k] = strtod(result_strings[k], NULL);
64 k++;
65 } while (k < LAPS);
66 });
67
68 for (i = 0; i < LAPS; i++) {
69 assert(results[i]);
70 }
71
72 printf( "\tserial cycles:\t%llu\n"
73 "\tapply() cycles:\t%llu\n"
74 "\tserial / concurrent: %.2Lf\n",
75 serial_cycles, concurrent_cycles,
76 (long double)serial_cycles / (long double)concurrent_cycles);
77
78 free(result_strings);
79 free(results);
80 }
81
82 int
83 main(void)
84 {
85 char path[PATH_MAX] = "/tmp/random_floats_XXXXXX";
86 struct stat sb;
87 double words[1000];
88 char buf[1024];
89 char *nums;
90 int fd, rfd;
91 size_t i, j;
92 ssize_t r;
93
94 rfd = open("/dev/random", O_RDONLY);
95 assert(rfd != -1);
96
97 fd = mkstemp(path);
98 assert(fd != -1);
99
100 r = unlink(path);
101 assert(r != -1);
102
103 i = 0;
104 do {
105 r = read(rfd, words, sizeof(words));
106 assert(r == sizeof(words));
107 for (j = 0; j < 1000; j++) {
108 if (isnormal(words[j])) {
109 r = write(fd, buf, snprintf(buf, sizeof(buf), "%.20e\n", words[j]));
110 assert(r != -1);
111 i++;
112 }
113 }
114 } while (i < MAXLAPS);
115
116 r = close(rfd);
117 assert(r != -1);
118
119 r = fstat(fd, &sb);
120 assert(r != -1);
121
122 nums = mmap(NULL, sb.st_size, PROT_READ, MAP_FILE|MAP_SHARED, fd, 0);
123 assert(nums != MAP_FAILED);
124
125 for (i = MAXLAPS; i > 0; i /= 2) {
126 test(i, nums);
127 }
128
129 r = munmap(nums, sb.st_size);
130 assert(r != -1);
131
132 r = close(fd);
133 assert(r != -1);
134
135 return 0;
136 }