C++用模板元编程进行循环展开的性能测试

27次阅读

共计 815 个字符,预计需要花费 3 分钟才能阅读完成。

在网上看到一篇 C ++ 模板元编程的文章,里面提到可以用来做循环展开,文章地址如下:https://www.2cto.com/kf/20120… 然后在 VS2015 里测了一下,测试代码如下:

template <int dim>
int get_sum(int* a) {
return a[0] + get_sum<dim – 1>(a + 1);
}

template <>
int get_sum<1>(int* a) {
return a[0];
}

int main() {
default_random_engine e;
const int n = 1000;
int vecs[n];
for (int &v : vecs) {
v = e() % 1000;
}

auto t1 = chrono::high_resolution_clock::now();
int s1 = 0;
for (int v : vecs) {
s1 += v;
}

auto t2 = chrono::high_resolution_clock::now();

//int s2 = Sum<n, int>::result(vecs);
int s2 = get_sum<n>(vecs);

auto t3 = chrono::high_resolution_clock::now();

auto d1 = chrono::duration_cast<chrono::microseconds>(t2 – t1);
auto d2 = chrono::duration_cast<chrono::microseconds>(t3 – t2);

printf(“%d, %d\n”, s1, s2);
printf(“%lld, %lld\n”, d1.count(), d2.count());

return 0;
}
代码也挺简单的,定义一个模板函数来做循环展开。然后比较循环加和展开后加的时间。选择 64 位,开启 O2 选项,不展开用时 1 微秒,展开用时 59 微秒。可见做这个展开意义不是特别大。而且当长度变大之后,编译器处理不了,展开会直接报编译错误。

正文完
 0