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

and*_*dge 0 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;
}
Run Code Online (Sandbox Code Playgroud)

现在,在-O3编译后在我的计算机上运行时,输出为

Elapsed time is 0.370000 seconds
Elapsed time is 1.170000 seconds
Run Code Online (Sandbox Code Playgroud)

如果我使用模板中注释掉的行,第二次是~1.8秒.我的问题是:如何加快操作员通话速度?理想情况下,它应该花费与手动编码循环相同的时间.

R. *_*des 8

你是按值传递参数的.这使得载体的副本.

template <typename T>
void operator^(vector<T> A, vector<T> B)
Run Code Online (Sandbox Code Playgroud)

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

template <typename T>
void operator^(vector<T> const& A, vector<T>& B)
Run Code Online (Sandbox Code Playgroud)

(对ideone.com的快速测试显示出比手写循环更好的性能,但我不知道它们在编译时启用了哪些优化.)

另外,您可能希望重载其他运算符.让非赋值和非增量运算符修改它们的参数是不好的风格(我建议阅读运算符重载常见问题解答).你应该重载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;
}
Run Code Online (Sandbox Code Playgroud)