gpt4 book ai didi

c++ - 性能对象属性与范围变量

转载 作者:行者123 更新时间:2023-11-28 05:43:03 25 4
gpt4 key购买 nike

这可能是一个初学者问题。

啊啊

class A
{
private:

short* arrObject;

public:
A();
~A();

void func0();
};

A.cpp

#include "A.h"
#include "Timer.h"
#include <iostream>

using namespace std;

A::A()
{
arrObject = new short[4];
}


A::~A()
{
}


void A::func0() {
Timer timer; // this class measures time in seconds

short* arrScope = new short[4];

timer.start();
for (int i = 0; i < 1000000; i++)
{
arrScope[3] = 987;
}
cout << "Writing in scope array " << timer.end() << endl;

timer.start();
for (int i = 0; i < 1000000; i++)
{
arrObject[3] = 987;
}
cout << "Writing in object array " << timer.end() << endl;

cout << endl;
}

A 的实例上调用 func0 产生输出:

Writing in scope array 0
Writing in object array 0.000771421

这意味着使用对象属性比使用范围变量慢。为什么会这样?

我使用的是 Visual Studio 2013,所以它是 Microsoft C/C++ 编译器。优化在VS中选择为“Maximize Speed/O2”

编辑:

另外,如果我把A.h改成:

class A
{
private:

short arrObject[4];

public:
A();
~A();

void func0();
};

并在 A.cpp 中丢失构造的初始化,差异消失,输出为:

Writing to scope array 0
Writing to object array 3.31082-007

最佳答案

好的,是的,这是优化问题。

如果我禁用所有优化,两个计时器都会显示准确的时间。另外,如果我保持优化并稍微弄乱代码:

void A::func0() {
Timer timer;

short* arrScope = new short[4];

timer.start();
for (int i = 0; i < 1000000; i++)
{
arrScope[i % 4] = i;
}
cout << "Writing in scope array " << timer.end() << endl;

timer.start();
for (int i = 0; i < 1000000; i++)
{
arrObject[i%4] = i;
}
cout << "Writing in object array " << timer.end() << endl;



cout << endl;
}

计时器也显示相同的时间。

Run #1: 0.00263972 / 0.00267415
Run #2: 0.00069362 / 0.00099159
Run #3: 0.00251192 / 0.00250728

关于c++ - 性能对象属性与范围变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36745689/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com