对向量的c++ operator()优化
C++ operator() optimization on vectors
我正在编写数字代码,其中定义向量操作很有用。例如,如果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
相关文章:
- 空基优化子对象的地址
- 关闭||运算符优化
- 如何解决gcc编译器优化导致的centos双编译器设置中的分段错误
- 返回值优化:显式移动还是隐式
- 为什么 std::optional::operator=(U&&) 要求你是非标量类型?
- 人脸跟踪arduino代码的优化
- 'operator='已弃用:改用 QDir::setPath()
- 使用仅使用一次的变量调用的复制构造函数.这可能是通过调用move构造函数进行编译器优化的情况吗
- 纯函数,为什么没有优化
- 过载'operator new'如何导致无限循环?
- 为什么大多数 pair 实现默认不使用压缩(空基优化)?
- 如何以优化的方式同时迭代两个间距不相等的数组
- 小字符串优化(调试与发布模式)
- 浮点定向舍入和优化
- Visual Studio 调试优化如何工作?
- 与'operator='不匹配(操作数类型'String'且"void")
- SegFault 同时使用 std::string::operator+= 和函数作为参数
- 为什么开关的优化方式与 c/c++ 中的链接不同?
- 优化' std::vector operator [] ' (vector访问),当它成为瓶颈时
- 对向量的c++ operator()优化