对向量的c++ operator()优化

C++ operator() optimization on vectors

本文关键字:优化 operator c++ 向量      更新时间:2023-10-16

我正在编写数字代码,其中定义向量操作很有用。例如,如果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 secondsn", double(t2-t1)/CLOCKS_PER_SEC);
  t1 = clock();
  for (int i=0; i<numRuns; i++)
    B^A;
  t2 = clock();
  printf("Elapsed time is %f secondsn", double(t2-t1)/CLOCKS_PER_SEC);
  return 0;
}

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

Elapsed time is 0.370000 seconds
Elapsed time is 1.170000 seconds

如果我在模板中使用注释掉的行,则第二次时间约为1.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上的一个快速测试显示比手写循环的性能更好,但我不知道它们在编译上启用了什么优化。)

另一个注意事项是,您可能希望重载其他操作符。让非赋值和非自增操作符修改它们的参数是一种糟糕的风格(我建议阅读操作符重载常见问题)。你应该重载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;
}

另一种想法是使用专门用于此目的的值数组,并且已经为您定义了大量操作符。

它们的用法和操作的描述可以在这里找到:http://www.cplusplus.com/reference/std/valarray/

关于它们的讨论可以在这里找到一些优缺点:c++ valarray与vector