0

我注意到,每次程序依赖while循环来保持打开状态时,它都会使用几乎 100% 的 CPU。添加 20 毫秒的延迟会使该数字降至 0%。

以下代码将最大化 CPU:

while(executing){
    // Do some things
    if(Quit) executing = 0;
}

但下一个不会:

while(executing){
    // Do some things        
    if(Quit) executing = 0;
    delayFunction(20); //20ms delay
}

这是正确的方法吗?如果是这样,什么会被认为是适当的延迟?

有没有更好的方法来避免 CPU 过载?

4

5 回答 5

1

A sheduler on the OS level take care of ditributing CPU ressources and time across processes.

Without the delay, the computer try to run the loop as fast as possible, so it use all ressources available for this process.

With a delay, you tell the sheduler that he has X msec to do other things. If no other process need processing time, then the CPU does nothing for this delay.

This is lot an issue, it's a feature. And there is no better way do to that. All the magic reside in the number of msec to wait. But it depends on many factors so it's impossible to be specific about that.

于 2013-08-09T11:01:55.093 回答
1

性能分析师的第一个答案是“视情况而定”。 有很多因素需要考虑,有些是自愿的yield()delay()看起来不错,有些则让它们看起来很糟糕。

  • 我们在谈论什么样的机器和任务?(使用收音机的循环会导致手机变得非常热。)
  • 手头的任务有多重要?(心脏监护仪必须按时采集和显示样本。)
  • 机器还在做什么?(VM 主机运行大量客户机,CPU 循环使其他进程饿死。)
  • 监督代码会抢占任务吗?(大多数操作系统会让更高优先级的任务在循环中接管。)
于 2013-08-09T11:14:46.633 回答
0

这两种“延迟技术”是不同的概念。首先,您所做的只是旋转 CPU,您的程序实际上在这些时刻在 CPU 上运行并消耗大量资源。

另一方面,在第二种情况下,您可以想象您的程序被搁置了 20 毫秒,而 CPU 在此期间可以做其他事情(或者只是保持空闲)。在后台发生的或多或少是一个睡眠系统调用

通常,您会希望使用第二种方法,因为它消耗的 CPU 更少。

于 2013-08-09T11:02:14.240 回答
0

您可以通过延迟实现更长的程序执行时间。操作系统负责进程之间的CPU共享。只要您不将进程优先级更改为实时并将线程优先级更改为最高,您就不必担心延迟

于 2013-08-09T11:03:44.787 回答
0

插入故意延迟有多种可能的原因。我曾经在填充一个非常大的数据库的早期阶段工作。虽然它仍然很小,但响应速度很快,但随着越来越多的数据添加到数据库中,显然预计会变慢。为了使用户的期望保持现实,我们在开始时设置了最短响应时间,这样用户就不会看到响应变慢。在不到 0.5 秒内返回的任何内容都会被保留,直到该最短时间过去,然后才发送给用户。

于 2013-08-09T14:02:13.270 回答