How to fix execution speed inconsistencies in C++

时间:2019-02-24 03:16:16

标签: c++

This is most noticeable on graphic files. Let's take as an example the OpenGL base program (a spinning triangle).

Whenever I run one normally, with no other apps open in the background, it will spin slowly, but when I run a game in the background, it starts spinning like mad. It seems as if the computer doesn't allocate enough memory for the programs to run at maximum speed, and paradoxically, doing resource-consuming stuff will accelerate it because it gets more memory.

The only way I found to fix this partially is to put a higher value in the Sleep function, however this doesn't fix it completely nor is a consistent solution, as other problems may arise from it. Is there any good way to fix this and make the program run consistently?

2 个答案:

答案 0 :(得分:0)

主要是因为您没有限制FPS,所以没有什么可以阻止渲染循环被尽可能多地调用以及您的逻辑(控制旋转在同一循环中执行)。

发生的事情是,大多数GPU都具有电源管理功能,因此在没有需求时它们会保持较低的频率,打开昂贵的游戏会使您的GPU发挥更大的性能,从而更快地渲染,从而使渲染循环次数更多。

要防止这种情况发生(通常将逻辑与渲染时间分开),必须控制帧频并将时间用作旋转输入,例如:

auto elapsed = ..
while (!exit) {
  render();
  auto delta = now - elapsed;
  if (delta  < time_per_frame)
    delay(TIME_PER_FRAME - delta);
  updateLogic(delta);
}

答案 1 :(得分:0)

对于初学者来说,您需要了解程序的运行情况。它与记忆没有任何关系,我看不出考虑记忆的理由。

  • 由于负载(已满,但显然比内存分配更有可能),因此打开其他程序可能会使CPU速度更快。

  • 其他程序可能会弄乱某些设置。

  • 如果您使用的是 .parent .child { display: table-cell; width : auto; padding: 5px; } ,则信号可能会中断调用(没有人看过该函数的返回代码;有理由将其设为sleep()而不是{ {1}}。

如果可以,请不要使用uint sleep(uint)。如果您要检查,请检查。 void sleep(uint)不会授予您已经过去了(恕我直言,糟糕的设计,但我不是POSIX爱好者)。

我认为通常的行为是定期调用您的函数作为回调。如果您要进行某种程度的延迟或睡眠,则应检查时间是否已到。

认为您希望将逻辑绑定到渲染器,并使用诸如sleep之类的可中断的功能(基于其他答案):

sleep