szsort_macros_test.c
1
2
3
4
5 #include "szsort_macros.h"
6
7 #include <assert.h>
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <time.h>
12
13
14 #define N (1 << 20)
15
16
17 typedef struct Key {
18 char s[8];
19 } Key;
20
21
22 Key Buf[N];
23
24
25 static unsigned char GetLetter(const Key *key, size_t depth) {
26 return (unsigned char)key->s[depth];
27 }
28
29
30 static void HandleSameKeys(Key *l, Key *r) {
31 }
32
33
34 DEFINE_SZSORT(StringSort, Key, GetLetter, HandleSameKeys);
35 DEFINE_HSZSORT(HugeStringSort, Key, GetLetter, HandleSameKeys);
36
37
38 static void Timer(int init) {
39 static clock_t cl;
40 if (init)
41 cl = clock();
42 else
43 printf("%f sec\n", 1.0 * (clock() - cl) / CLOCKS_PER_SEC);
44 }
45
46
47 static void RandomizeKey(Key *key) {
48 size_t i;
49 for (i = 0; i < sizeof(key->s) - 1; i++)
50 key->s[i] = '0' + rand() % 10;
51 key->s[i] = '\0';
52 }
53
54
55 static void RandomizeBuffer(Key *buf, size_t n) {
56 size_t i;
57 for (i = 0; i < n; i++)
58 RandomizeKey(buf + i);
59 }
60
61
62 static void IsSorted(const Key *key, size_t n) {
63 size_t i;
64 for (i = 1; i < n; i++)
65 assert(strcmp(key[i - 1].s, key[i].s) <= 0);
66 }
67
68 int main(void) {
69 Key *keys;
70
71 srand((unsigned)time(NULL));
72
73 RandomizeBuffer(Buf, N);
74
75
76 Timer(1);
77 keys = HugeStringSort(Buf, Buf + N, 0);
78 if (keys != NULL) {
79 Timer(0);
80 IsSorted(keys, N);
81 free(keys);
82 }
83
84
85 Timer(1);
86 StringSort(Buf, Buf + N, 0);
87 Timer(0);
88 IsSorted(Buf, N);
89
90 return 0;
91 }