为什么繁忙循环会占用 100% 的 CPU?

发布于 2024-11-04 03:07:05 字数 73 浏览 1 评论 0原文


为什么繁忙的循环经常使用 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

小女人ら 2024-11-11 03:07:06

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.

会发光的星星闪亮亮i 2024-11-11 03:07:06

一个复杂的算法当然可以使用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.

简单 2024-11-11 03:07:06

首先,如果你的繁忙循环使用了 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%.

冷了相思 2024-11-11 03:07:06

“繁忙循环”不必与内存通信,因此 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.

撕心裂肺的伤痛 2024-11-11 03:07:06

取决于“复杂算法”正在做什么。它可以访问硬盘吗?网络请求?与任何其他硬件交互?当发生这种情况时,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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文