szpool_test.cpp
1
2
3
4 #include "szpool.h"
5
6
7 #include <cstdio>
8
9 #include <cstring>
10
11 #include <ctime>
12
13
14 #include <vector>
15
16
17 namespace {
18
19 using std::size_t;
20
21 class Timer {
22 public:
23 Timer() { cl_ = clock(); }
24 ~Timer() { printf("Time: %.3f\n", 1.0 * (clock() - cl_) / CLOCKS_PER_SEC); }
25 private:
26 clock_t cl_;
27 };
28
29
30 static const size_t Count = 1 << 22;
31
32
33 static void TestOK() {
34 StringPool::Pool<char> pool;
35 std::vector<const char *> keys;
36
37
38 for (size_t i = 0; i < Count; ++i) {
39 char s[12];
40 sprintf(s, "%010d", i);
41 keys.push_back(pool.add(s));
42 }
43
44
45 for (size_t i = 0; i < Count; ++i) {
46 char s[12];
47 sprintf(s, "%010d", i);
48 assert(!strcmp(s, keys[i]));
49 }
50 }
51
52
53 template <typename Letter>
54 static void TestPool() {
55 printf("\n- StringPool::Pool (%d-bit)\n", sizeof(Letter) << 3);
56
57 Timer timer;
58 StringPool::Pool<Letter> pool;
59
60
61 char s[] = "Apple juice";
62 for (size_t i = 0; i < Count; ++i)
63 pool.add(s);
64
65 printf("Number of strings: %u\n", pool.num_strs());
66 printf("Total size: %u\n", pool.total_size());
67 }
68
69
70 static void TestNewAndDelete() {
71 printf("\n- new [] and delete [] for each char string\n");
72
73 Timer timer;
74
75
76 char s[] = "Apple juice";
77 size_t size = strlen(s) + 1;
78 for (size_t i = 0; i < Count; ++i) {
79 char *buf = new char[size];
80 memcpy(buf, s, size);
81 delete [] buf;
82 }
83 }
84
85 }
86
87
88 int main(void) {
89 TestOK();
90
91 TestPool<char>();
92 TestPool<short>();
93 TestPool<int>();
94
95 TestNewAndDelete();
96
97 return 0;
98 }