向量上的C ++ operator()优化

时间:2011-09-25 21:18:48

标签: c++ algorithm optimization operators

我正在编写数字代码,其中定义向量操作很有用。例如,如果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秒。 我的问题是:如何加快操作员通话速度?理想情况下,它应该花费与手动编码循环相同的时间。

2 个答案:

答案 0 :(得分:8)

您按值传递参数。这就是载体的副本。

template <typename T>
void operator^(vector<T> A, vector<T> B)

如果您通过引用传递它们,您可能会获得加速。

template <typename T>
void operator^(vector<T> const& A, vector<T>& B)

(对于ideone.com的快速测试显示even better performance而不是手写循环,但我不知道它们在编译时启用了哪些优化。)

另一方面,您可能希望重载其他运算符。让非赋值和非增量运算符修改它们的参数是不好的风格(我建议阅读Operator Overloading FAQ)。您应该重载operator^=

template <typename T>
vector<T>& operator^=(vector<T>& B, vector<T> const& A){
  typename vector<T>::const_iterator a = A.begin();
  typename vector<T>::iterator b = B.begin();
  while(a!=A.end()){
    *b = 2*(*a);
    a++; b++;
  }
  return B;
}

答案 1 :(得分:0)

另一个想法是使用valarray,它专门用于此目的,并且已经为您定义了大量的运算符。

可在此处找到有关其用法和操作的说明:http://www.cplusplus.com/reference/std/valarray/

可以在这里找到对它们的讨论,说明一些优点和缺点:C++ valarray vs. vector