-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathbenchmark.cpp
More file actions
95 lines (84 loc) · 2.59 KB
/
benchmark.cpp
File metadata and controls
95 lines (84 loc) · 2.59 KB
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
#include "Function.h"
#include <chrono>
#include <iostream>
int main(int argc, char *argv[]) {
constexpr size_t count = 100000000;
using namespace std::chrono;
volatile size_t state = 0;
struct State {
size_t a, b, c;
};
State state2 = {0, 0, 0};
std::cout << "construction overhead" << std::endl;
{
auto start = high_resolution_clock::now();
for (size_t i = 0; i < count; ++i) {
std::function<void()> stdfun = [&state, state2, i]() { state = i; };
stdfun();
}
auto stop = high_resolution_clock::now();
auto duration = stop - start;
std::cout << "std::function: "
<< duration_cast<nanoseconds>(duration).count() / count << "ns/op"
<< std::endl;
}
{
auto start = high_resolution_clock::now();
for (size_t i = 0; i < count; ++i) {
Function<void()> fun = [&state, state2, i]() { state = i; };
fun();
}
auto stop = high_resolution_clock::now();
auto duration = stop - start;
std::cout << "Function: "
<< duration_cast<nanoseconds>(duration).count() / count << "ns/op"
<< std::endl;
}
std::cout << "invokation overhead" << std::endl;
{
std::function<void(size_t)> stdfun([&state](size_t i) { state = i; });
auto start = high_resolution_clock::now();
for (size_t i = 0; i < count; ++i) {
stdfun(i);
}
auto stop = high_resolution_clock::now();
auto duration = stop - start;
std::cout << "std::function: "
<< duration_cast<nanoseconds>(duration).count() / count << "ns/op"
<< std::endl;
}
{
Function<void(size_t)> fun([&state](size_t i) { state = i; });
auto start = high_resolution_clock::now();
for (size_t i = 0; i < count; ++i) {
fun(i);
}
auto stop = high_resolution_clock::now();
auto duration = stop - start;
std::cout << "Function: "
<< duration_cast<nanoseconds>(duration).count() / count << "ns/op"
<< std::endl;
}
{
// Must compile this with -fno-devirtualize to prevent inlining
struct Fun {
virtual void fun(size_t) = 0;
};
struct Impl : public Fun {
void fun(size_t i) override { state = i; };
volatile size_t state = 0;
};
Impl impl;
auto start = high_resolution_clock::now();
for (size_t i = 0; i < count; ++i) {
Fun *fun = &impl;
fun->fun(i);
}
auto stop = high_resolution_clock::now();
auto duration = stop - start;
std::cout << "virtual: "
<< duration_cast<nanoseconds>(duration).count() / count << "ns/op"
<< std::endl;
}
return 0;
}