szsort_macros_test.c
 1  // This sample code tests the performance of sorting provided by
 2  // "szsort_macros.h." Random 7-letters strings are sorted by
 3  // HugeStringSort(), StringSort() and qsort().
 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  // Buffer size (how many keys are in the buffer).
14  #define N (1 << 20)
15  
16  // Key type.
17  typedef struct Key {
18    char s[8];
19  } Key;
20  
21  // Buffer to be sorted.
22  Key Buf[N];
23  
24  // Function to get a letter from a Key.
25  static unsigned char GetLetter(const Key *key, size_t depth) {
26    return (unsigned char)key->s[depth];
27  }
28  
29  // Function to handle same keys found in sorting.
30  static void HandleSameKeys(Key *l, Key *r) {
31  }
32  
33  // Define functions to sort an array of Keys.
34  DEFINE_SZSORT(StringSort, Key, GetLetter, HandleSameKeys);
35  DEFINE_HSZSORT(HugeStringSort, Key, GetLetter, HandleSameKeys);
36  
37  // Timer.
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  // Randomize a Key.
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  // Randomize Keys in buffer.
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  // Confirm that an array is sorted.
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    // Test of HugeStringSort().
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    // Test of StringSort().
85    Timer(1);
86    StringSort(Buf, Buf + N, 0);
87    Timer(0);
88    IsSorted(Buf, N);
89  
90    return 0;
91  }