【问题标题】:Accessing variables of an object slowing down program (C++)访问对象的变量减慢程序(C++)
【发布时间】:2014-01-04 18:13:28
【问题描述】:

我正在编写一个循环通过向量的模拟。在代码中,它执行一个操作,每次迭代计算 2 个对象的 delta x 和 y。我正在处理的代码:

for(unsigned z = 0; z < creatures.size(); z++) {
    for(unsigned z2 = 0; z2 < creatures.size(); z2++) {
        if(z != z2) {
            int delta_x = creatures[z2].xpos - creatures[z].xpos;
            int delta_y = creatures[z2].ypos - creatures[z].ypos;
        }
    }
}

这是类:

class Creature {
    public:
        int xpos;
        int ypos;
        ...
};

还有其他代码,但不会对性能产生太大影响。我注意到,如果我将增量​​的分配更改为数字甚至减法运算(例如 z-z2 或类似的东西),它会将程序的“FPS”从 ~5 提高到 ~7/8。有什么办法可以加快这个操作?

【问题讨论】:

  • 您确定这是对性能有影响的代码吗?对我来说,这似乎并不昂贵。
  • creatures 定义在哪里?
  • @EdHeal Vector: vector&lt;Creature&gt; creatures; 类本身在头文件中定义。
  • 使用分析器来识别程序的瓶颈。
  • 您是在为使用编译器优化选项构建的代码计时,还是在为调试构建计时?由于迭代器和/或访问器的大量验证,调试构建中的 STL 容器访问通常会非常缓慢。

标签: c++ class loops optimization vector


【解决方案1】:

跟随可能更快

const std::size_t size = creatures.size();
for (unsigned z = 0; z + 1 < size; z++) {
    const int zx = creatures[z].xpos;
    const int zy = creatures[z].ypos;
    for (unsigned z2 = z + 1; z2 < size; z2++) {
            const int delta_x = creatures[z2].xpos - zx;
            const int delta_y = creatures[z2].ypos - zy;
    }
}
  • creatures[z].xpos移出循环。
  • creatures.size()移出循环。
  • 由于 {z, z2} 对与 {z2, z} 对称,因此将作业分组。

编辑creatures.size() 移出循环(感谢 shawn1874

【讨论】:

  • 哇,不敢相信我没想到。太感谢了!让我走到了一半,但我认为我可以在其他地方实现这个想法,以从这个程序中获得更多的性能。我想知道为什么访问类变量会占用这么多时间...
  • 您是否也尝试过使用迭代器或在循环外仅调用一次 size ?如果过度访问属性会导致性能问题,那么一遍又一遍地调用成员函数肯定不会有帮助。 size_t theSize = 生物.size()
猜你喜欢
  • 2022-11-23
  • 2012-03-11
  • 1970-01-01
  • 2011-12-04
  • 2012-07-05
  • 2015-09-22
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
相关资源
最近更新 更多