/
Main.cpp
144 lines (125 loc) · 2.75 KB
/
Main.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#include "Stopwatch.h"
#include "Hashtable.h"
#include <string>
#include <sstream>
using namespace std;
using namespace Words;
template<typename TFunc>
float MeasureN(TFunc func, int n)
{
Stopwatch watch;
for (int i = 0; i < n; ++i)
{
func();
}
return watch.elapsed();
}
template<typename TFunc>
int TrialMeasure(TFunc func)
{
int count = 2;
float elapsed;
do
{
count *= 2;
elapsed = MeasureN(func, count);
} while (elapsed < 0.01f);
return count;
}
template<typename TFunc>
void Measure(const char* name, TFunc func)
{
int n = TrialMeasure(func);
double totalUsecs = 0.0;
int ops = 0;
for (int i = 0; i < 10; ++i)
{
double secs = static_cast<double>(MeasureN(func, n));
totalUsecs += secs * 1000000;
ops += n;
}
double avgUsecs = totalUsecs / ops;
printf("%s : % 10.3f usec per op\n", name, avgUsecs);
}
void MakeKey(char* k, int v)
{
for (int i = 0; i < 4; ++i)
{
k[i] = 'a' + (v % 26);
v /= 26;
}
}
void Fill(Hashtable<string, int>& table, int n)
{
char raw[5];
raw[4] = '\0';
for (int i = 1; i <= n; ++i)
{
MakeKey(raw, i);
string key(raw);
table.insert(key, i);
}
}
void Insert(Hashtable<string, int>& table, int n, float f)
{
table = Hashtable<string, int>(f);
Fill(table, n);
}
int FindPresent(const Hashtable<string, int>& table, int n)
{
char raw[5];
raw[4] = '\0';
int sum = 0;
for (int i = 1; i <= n; ++i)
{
MakeKey(raw, i);
string key(raw);
int v;
if (table.get(key, v))
{
sum += v;
}
}
return sum;
}
int FindMissing(const Hashtable<string, int>& table, int n)
{
char raw[6];
raw[4] = '_';
raw[5] = '\0';
int sum = 0;
for (int i = 1; i <= n; ++i)
{
MakeKey(raw, i);
string key(raw);
int v;
if (table.get(key, v))
{
sum += v;
}
}
return sum;
}
int main()
{
for (int i = 1; i <= 4; ++i)
{
float f = i / 4.0f;
int n = 1;
for (int j = 1; j <= 5; ++j)
{
n *= 10;
Hashtable<string, int> table(f);
stringstream s;
s << " Insert_1e" << j << "_" << i << "/4";
Measure(s.str().c_str(), [&table, n, f]() { Insert(table, n, f); });
s = stringstream();
s << "FindPresent_1e" << j << "_" << i << "/4";
Measure(s.str().c_str(), [&table, n]() { FindPresent(table, n); });
s = stringstream();
s << "FindMissing_1e" << j << "_" << i << "/4";
Measure(s.str().c_str(), [&table, n]() { FindMissing(table, n); });
}
}
return 0;
}