1 /* Simple speed tests for a hash of strings using hsearch */
2 #include <ccan/htable/htable_type.h>
3 #include <ccan/htable/htable.c>
4 #include <ccan/str_talloc/str_talloc.h>
5 #include <ccan/grab_file/grab_file.h>
6 #include <ccan/talloc/talloc.h>
7 #include <ccan/hash/hash.h>
8 #include <ccan/time/time.h>
17 /* Nanoseconds per operation */
18 static size_t normalize(const struct timeval
*start
,
19 const struct timeval
*stop
,
24 timersub(stop
, start
, &diff
);
26 /* Floating point is more accurate here. */
27 return (double)(diff
.tv_sec
* 1000000 + diff
.tv_usec
)
31 int main(int argc
, char *argv
[])
34 struct timeval start
, stop
;
36 ENTRY
*words
, *misswords
;
38 w
= strsplit(NULL
, grab_file(NULL
,
39 argv
[1] ? argv
[1] : "/usr/share/dict/words",
41 num
= talloc_array_length(w
) - 1;
42 printf("%zu words\n", num
);
46 words
= talloc_array(w
, ENTRY
, num
);
47 for (i
= 0; i
< num
; i
++) {
49 words
[i
].data
= words
[i
].key
;
52 /* Append and prepend last char for miss testing. */
53 misswords
= talloc_array(w
, ENTRY
, num
);
54 for (i
= 0; i
< num
; i
++) {
57 lastc
= w
[i
][strlen(w
[i
])-1];
60 misswords
[i
].key
= talloc_asprintf(misswords
, "%c%s%c%c",
65 printf("#01: Initial insert: ");
68 for (i
= 0; i
< num
; i
++)
69 hsearch(words
[i
], ENTER
);
71 printf(" %zu ns\n", normalize(&start
, &stop
, num
));
73 printf("#02: Initial lookup (match): ");
76 for (i
= 0; i
< num
; i
++)
77 if (hsearch(words
[i
], FIND
)->data
!= words
[i
].data
)
80 printf(" %zu ns\n", normalize(&start
, &stop
, num
));
82 printf("#03: Initial lookup (miss): ");
85 for (i
= 0; i
< num
; i
++) {
86 if (hsearch(misswords
[i
], FIND
))
90 printf(" %zu ns\n", normalize(&start
, &stop
, num
));
92 /* Lookups in order are very cache-friendly for judy; try random */
93 printf("#04: Initial lookup (random): ");
96 for (i
= 0, j
= 0; i
< num
; i
++, j
= (j
+ 10007) % num
)
97 if (hsearch(words
[i
], FIND
)->data
!= words
[i
].data
)
100 printf(" %zu ns\n", normalize(&start
, &stop
, num
));