我刚刚开始实现自己的 vector 类,我正在使用一个简单的文件对其进行测试,以检查完成所需的时间。一项测试用时 2 分 30 秒,而其他测试用时 90 秒 29 秒。
有些东西影响了这个类的性能。能帮我追根溯源吗?
测试:
#include "MyVector.h"
const unsigned int SIZE_V= 1000000;
const unsigned int RUNS= 10000;
int main() {
MyVector v(SIZE_V);
for (unsigned int j=0; j<RUNS; ++j) {
for (unsigned int i=0; i<SIZE_V; ++i) {
v[i]= i;
}
}
return 0;
}
类(class):
MyVector.h:
#ifndef MY_VECTOR_H
#define MY_VECTOR_H
class MyVector {
public:
MyVector(unsigned int size);
~MyVector();
int& operator[](unsigned int i);
private:
int* _data;
unsigned int _size;
MyVector(const MyVector&);
MyVector& operator=(const MyVector&);
};
#endif
MyVector.cpp:
#include "MyVector.h"
#include <assert.h>
MyVector::MyVector(unsigned int size) : _data(new int[size]) {
}
MyVector::~MyVector() {
delete[] _data;
}
int& MyVector::operator[](unsigned int i) {
assert(i<_size);
return _data[i];
}
编辑:
这些是测试结果:
granularity: each sample hit covers 4 byte(s) for 0.04% of 27.09 seconds
index % time self children called name
<spontaneous>
[1] 100.0 12.51 14.58 main [1]
11.28 0.00 1410065408/1410065408 MyVector::operator[](unsigned int) [2]
3.31 0.00 1/1 MyVector::~MyVector() [3]
0.00 0.00 1/1 MyVector::MyVector(unsigned int) [7]
-----------------------------------------------
11.28 0.00 1410065408/1410065408 main [1]
[2] 41.6 11.28 0.00 1410065408 MyVector::operator[](unsigned int) [2]
-----------------------------------------------
3.31 0.00 1/1 main [1]
[3] 12.2 3.31 0.00 1 MyVector::~MyVector() [3]
-----------------------------------------------
0.00 0.00 1/1 main [1]
[7] 0.0 0.00 0.00 1 MyVector::MyVector(unsigned int) [7]
-----------------------------------------------
最佳答案
您可能想要做的一件事是使 operator[]
内联。当我这样做时,你的代码在我的盒子上的性能从
real 0m18.270s
到
real 0m6.030s
在后一个测试中,测试循环的每次迭代大约需要 0.6ns (!) 或大约 1.5 个时钟周期。
这是在使用 g++ 4.7.2 和 -O3
的 Sandy Bridge 盒子上。
附言代码中存在错误:构造函数未初始化 _size
,因此 assert()
具有未定义的行为。
关于c++ - 在简单的 vector 实现中优化运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14497713/