×

[PR]この広告は3ヶ月以上更新がないため表示されています。
ホームページを更新後24時間以内に表示されなくなります。

szpool_test.cpp
 1  //
 2  // Test codes for StringPool.
 3  //
 4  #include "szpool.h"
 5  
 6  // For std::size_t and printf().
 7  #include <cstdio>
 8  // For strlen() and memcpy().
 9  #include <cstring>
10  // For clock_t and clock().
11  #include <ctime>
12  
13  // For vector.
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  // Number of strings to be added.
30  static const size_t Count = 1 << 22;
31  
32  // Test if StringPool::Pool works well.
33  static void TestOK() {
34    StringPool::Pool<char> pool;
35    std::vector<const char *> keys;
36  
37    // Add numbers.
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    // Check numbers.
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  // Test the performance of StringPool::Pool.
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    // Add the same string many times.
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  // Test the case using a pair of new [] and delete[] for each string.
70  static void TestNewAndDelete() {
71    printf("\n- new [] and delete [] for each char string\n");
72  
73    Timer timer;
74  
75    // Repeat new [] and delete [].
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  }  // namespace.
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  }