【发布时间】:2011-09-25 21:18:47
【问题描述】:
我正在编写数字代码,其中定义向量运算很有用。例如,如果 x 和 y 是充满浮点数的 n 长向量,最好让 x^y 导致 y 的第 i 个元素中的 a 等于 x 的第 i 个元素的某个任意函数。一种简单的方法是:
#include <vector>
#include <stdio.h>
#include <ctime>
using namespace std;
template <typename T>
void operator^(vector<T> A, vector<T> B){
typename vector<T>::iterator a = A.begin();
typename vector<T>::iterator b = B.begin();
while(a!=A.end()){
*b = 2*(*a);
a++; b++;
}
//for (uint i=0; i<A.size(); i++)
//B[i] = 2*A[i];
}
int main(int argc, char** argv){
int n = 10000;
int numRuns = 100000;
vector<float> A;
for (int i=0; i<n; i++)
A.push_back((float) i);
vector<float> B = vector<float>(n);
clock_t t1 = clock();
for (int i=0; i<numRuns; i++)
for (int j=0; j<n; j++)
B[j] = 2*A[j];
clock_t t2 = clock();
printf("Elapsed time is %f seconds\n", double(t2-t1)/CLOCKS_PER_SEC);
t1 = clock();
for (int i=0; i<numRuns; i++)
B^A;
t2 = clock();
printf("Elapsed time is %f seconds\n", double(t2-t1)/CLOCKS_PER_SEC);
return 0;
}
现在,当 -O3 编译后在我的电脑上运行时,输出是
Elapsed time is 0.370000 seconds
Elapsed time is 1.170000 seconds
如果我使用模板中注释掉的行,第二次是 ~1.8 秒。 我的问题是:如何加快接线员的通话速度?理想情况下,它应该花费与手动编码循环相同的时间。
【问题讨论】:
-
C 和 C++ 不是同一种语言。如果是,我们可能会为它们使用相同的标签。
-
不要编写运算符来执行此操作。写一个函数。这样做是运算符重载声名狼藉的原因之一。当您让操作员执行所有人(除了您之外)意想不到的事情时,代码几乎无法阅读。
标签: c++ algorithm optimization operators