【发布时间】:2017-01-05 12:25:39
【问题描述】:
我根据在http://www.umich.edu/~eecs381/handouts/C++11_smart_ptrs.pdf 中阅读的信息进行了一些测试
测量的目的是检查shared_ptr的单分配和双分配(坏样式)消耗了多少时间。我认为单次分配应该比双次分配更省时。 所以我想知道我是否误解了某事或内存分配与时间无关。
测试代码:
#include <iostream>
#include <memory>
#include <chrono>
#include <string>
using namespace std;
class Test{
private:
int value;
string name;
double value2;
public:
Test(int v, string n, double v2) : value(v), name(n), value2(v2){}
~Test(){}
};
void singleAllocation(){
chrono::system_clock::time_point start = chrono::system_clock::now();
for(int i = 0; i < 3000; i++)
shared_ptr<Test> sp(make_shared<Test>(10, "This is simple test", 2.3334));
chrono::system_clock::time_point end = chrono::system_clock::now();
cout<<"single allocation of 3000 objects took "
<<chrono::duration_cast<chrono::microseconds>(end - start).count()
<<"us.\n";
}
void doubleAllocation(){
chrono::system_clock::time_point start = chrono::system_clock::now();
for(int i = 0; i < 3000; i++)
shared_ptr<Test> sp(new Test(10, "This is simple test", 2.3334));
correlaction
chrono::system_clock::time_point end = chrono::system_clock::now();
cout<<"\n\ndouble allocation of 3000 objects took "
<<chrono::duration_cast<chrono::microseconds>(end - start).count()
<<"us.\n";
}
int main(){
singleAllocation();
doubleAllocation();
}
输出: 3000 个对象的单次分配耗时 2483us。
3000 个对象的双重分配耗时 1226us。
【问题讨论】:
-
我刚刚编译并运行了您的代码,并进行了更多迭代 (3000000)。单次分配总是更快:单次分配需要 1.04 秒,双次分配需要 1.23 秒。你是在 Release 模式下编译的吗?
-
我已经编译使用:g++ --std=c++11 file.cpp -o file.out
-
如果您通过在
--std=c++11之后添加-O3来启用优化,可能会有所帮助。不幸的是,我在 Windows 上,所以我现在无法尝试。 -
现在我用:g++ --std=c++11 -O3 file.cpp -o file.out 编译得到:300万个对象的单次分配花费了244255us。 300 万个对象的双重分配花费了 310464us。但是当不使用优化时,仍然双倍更快。
-
@Lukasz 除非未优化的情况慢 10 倍,否则这不是一个有趣的变化。未优化的意思是“我不在乎速度,我想要轻松通过装配”。
标签: c++11 shared-ptr