Skip to content

Commit b6d0329

Browse files
committed
C++/Cpp11Range: Add benchmark for range
1 parent 23bf4b9 commit b6d0329

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

C++/Cpp11Range/main.cpp

+35
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
#include "pch.h"
22

3+
#include <chrono>
4+
35
template<typename T>
46
class RangeObj {
57
public:
@@ -59,6 +61,18 @@ RangeObj<T> range(T end) {
5961
return range(T(), end);
6062
}
6163

64+
class Timer {
65+
public:
66+
Timer(const char *name): mName(name), mStart(chrono::high_resolution_clock::now()) {
67+
}
68+
~Timer() {
69+
printf("%s: %.3f\n", mName, chrono::duration<double>(chrono::high_resolution_clock::now() - mStart).count());
70+
}
71+
private:
72+
const char *mName;
73+
chrono::high_resolution_clock::time_point mStart;
74+
};
75+
6276
int main() {
6377
for (auto i : range(5)) printf("%d,", i);
6478
puts("");
@@ -77,4 +91,25 @@ int main() {
7791

7892
for (auto i : range<float>(3, 0, -0.5)) printf("%.2f,", i);
7993
puts("");
94+
95+
const int LOOP = 1024;
96+
const int N = 1024 * 1024;
97+
int r = 0;
98+
{
99+
Timer _t("for");
100+
for (int i = 0; i < LOOP; ++i) {
101+
for (int i = 0; i < N; ++i) r += i & 0x123;
102+
}
103+
}
104+
105+
int r2 = 0;
106+
{
107+
Timer _t("range");
108+
for (int i = 0; i < LOOP; ++i) {
109+
for (int i : range(N)) r2 += i & 0x123;
110+
}
111+
}
112+
assert(r == r2);
113+
114+
return r - r2;
80115
}

0 commit comments

Comments
 (0)