最近学习了CRTP(Curiously Recurring Template Pattern)技术,并尝试将其放入工程中,以取代虚表。但同事对这一技术表示怀疑,并执意要做实验测量经过CRTP“优化”后的代码与虚表方式的代码的速度差异,于是就有了下面这套代码

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

#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>

class Base1 {
public:
volatile long long int counter = 0;
virtual void foo() {
abort();
}
};

class Derived1 : public Base1 {
public:
void foo() {
counter++;
}
};

template <typename T>
class Base2 {
public:
volatile long long int counter = 0;
void foo() {
static_cast<T *>(this)->foo_impl();
}
};

class Derived2 : public Base2<Derived2> {
public:
void foo_impl() {
counter++;
}
};

long timestamp() {
struct timeval tv;
gettimeofday(&tv, NULL);
return (tv.tv_sec * 1000000 + tv.tv_usec);
}

long test1() {
Derived1 d1;
long start = timestamp();
for (int i = 0; i < 1000000; i++) {
d1.foo();
}
return timestamp() - start;
}

long test2() {
Derived2 d2;
long start = timestamp();
for (int i = 0; i < 1000000; i++) {
d2.foo();
}
return timestamp() - start;
}

int main() {
printf("%ld\t%ld\n", test1(), test2());
}

不进行任何优化,虚表的速度竟大于CRTP的速度,而在O1优化下,两个方法的速度趋于一致。