我正在阅读《C++模板完全指南》这本书,其中涉及到元编程的部分。在第17.7节中有一个循环展开的例子。我已经为点积计算实现了该程序:
#include <iostream>
#include <sys/time.h>
using namespace std;
template<int DIM, typename T>
struct Functor
{
static T dot_product(T *a, T *b)
{
return *a * *b + Functor<DIM - 1, T>::dot_product(a + 1, b + 1);
}
};
template<typename T>
struct Functor<1, T>
{
static T dot_product(T *a, T *b)
{
return *a * *b;
}
};
template<int DIM, typename T>
T dot_product(T *a, T *b)
{
return Functor<DIM, T>::dot_product(a, b);
}
double dot_product(int DIM, double *a, double *b)
{
double res = 0;
for (int i = 0; i < DIM; ++i)
{
res += a[i] * b[i];
}
return res;
}
int main(int argc, const char * argv[])
{
static const int DIM = 100;
double a[DIM];
double b[DIM];
for (int i = 0; i < DIM; ++i)
{
a[i] = i;
b[i] = i;
}
{
timeval startTime;
gettimeofday(&startTime, 0);
for (int i = 0; i < 100000; ++i)
{
double res = dot_product<DIM>(a, b);
//double res = dot_product(DIM, a, b);
}
timeval endTime;
gettimeofday(&endTime, 0);
double tS = startTime.tv_sec * 1000000 + startTime.tv_usec;
double tE = endTime.tv_sec * 1000000 + endTime.tv_usec;
cout << "template time: " << tE - tS << endl;
}
{
timeval startTime;
gettimeofday(&startTime, 0);
for (int i = 0; i < 100000; ++i)
{
double res = dot_product(DIM, a, b);
}
timeval endTime;
gettimeofday(&endTime, 0);
double tS = startTime.tv_sec * 1000000 + startTime.tv_usec;
double tE = endTime.tv_sec * 1000000 + endTime.tv_usec;
cout << "loop time: " << tE - tS << endl;
}
return 0;
}
我正在使用Xcode,并关闭了所有代码优化。根据这本书,我预计模板版本应该比简单循环更快。但结果是(t-模板,l=循环):
DIM 5:t = ~5000,l = ~3500
DIM 50:t = ~55000,l = 16000
DIM 100:t = 130000,l = 36000
我还尝试将模板函数设置为内联,但没有性能差异。
为什么简单循环会快得多呢?
dot_product
的实例没有被内联,那么调用它们将比运行循环慢得多。 - Mike Seymour