为什么繁忙循环会占用 100% 的 CPU?
为什么繁忙的循环经常使用 100% 的 CPU 时间,而实现复杂算法的循环则使用更少的 CPU 时间?
谢谢 :)
Why does a busy loop often uses 100% of the cpu time while loops that implement complex algorithms would use much much less?
thanks :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
CPU 架构中的 JUMP 指令效率低下,因为它们会导致管道刷新。繁忙循环实际上是无限系列的 JUMP 指令。
JUMP instructions in the CPU architecture are inefficient because they cause the pipeline to flush. A busy loop is effectively an infinite series of JUMP instructions.
一个复杂的算法当然可以使用100%的cpu。然而,许多实现复杂算法的循环要么定期显式地产生线程,要么有一些代码在某个时刻向下调用操作系统,其中要么产生线程,要么需要等待(例如调用一个协程)。处理器)发生。
A complex algorithm can certainly use 100% of the cpu. However, many loops that implement complex algorithms either explicitly yield the thread periodically and/or have some code that calls down into the OS at some point, where either the thread is yielded or something that requires a wait (such as calling on a co-processor) happens.
首先,如果你的繁忙循环使用了 100%,那么你就没有做对。睡一会儿。
其次,复杂的算法通常涉及内存来存储值,而不仅仅是循环。每当线程需要使用外部资源(如内存、磁盘等)时,CPU 都必须等待一段时间。这就是为什么您会看到它的使用率低于 100%。
First, if your busy loop uses 100% then you aren't doing it right. Sleep for a bit.
Second, complex algorithms often involve memory to store values as opposed to just looping. Any time the thread needs to use an external resource like memory, disk, etc. the CPU has to wait a bit. This is why you would see it use less than 100%.
“繁忙循环”不必与内存通信,因此 CPU 基本上自己完成所有工作,无需等待外部输入。
A "busy loop" does not have to talk to memory, so the CPU is basically doing all work itself without waiting for external input.
取决于“复杂算法”正在做什么。它可以访问硬盘吗?网络请求?与任何其他硬件交互?当发生这种情况时,CPU 将不得不等待这些事情完成,因此它在等待信息返回时什么也不做(或者执行上下文切换到其他工作)。
Depends what that "complex algorithm" is doing. Does it do Hard Drive access? Network requests? Interact with any other hardware? When that happens the CPU will have to wait for those things to complete, so it sits around doing nothing (or does a context switch to some other work) while it waits for that information to come back.