性能对象属性与范围变量
Performance object properties vs scope variables
这可能是一个初学者的问题。
啊
class A
{
private:
short* arrObject;
public:
A();
~A();
void func0();
};
答.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中选择为"最大化速度/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++从实例范围之外的分隔 std::function 变量调用
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 如果非动态变量被指针引用,何时超出范围?
- 为什么我的变量存在于其范围之外
- 变量超出范围后如何保留向量值?
- 将引用分配给局部变量,如果局部变量超出范围,它会超出范围吗?
- 在C++中使用变量而不是"#define"来指定数组大小是不是一种糟糕的做法?(C错误:在文件范围内
- 在 c++ 中确定堆栈上的变量范围
- 如何改进一堆在已知值范围内评估变量的 else-if 条件?
- 如何从未知视图中声明范围::v3::View 变量
- 如果变量数据包含大于 vector 所有元素的整数,则仅在视觉工作室上接收"矢量下标超出范围"?
- 是否未定义将对函数范围变量的引用作为值返回
- 无法从另一个函数访问文件范围变量的内容
- 如何访问C 中的功能范围变量
- C++ 程序和范围变量
- 性能对象属性与范围变量
- 存储lambda函数,该函数将范围变量捕获为类成员以供重用
- 何时分配块范围变量
- 在 c++ 中声明一个全局范围变量 const