为什么意外的无限循环会增加 CPU 使用率?

发布于 2024-09-01 23:02:22 字数 55 浏览 9 评论 0原文

我知道意外的无限循环通常会导致 CPU 使用率较高。但是,我不太明白为什么。谁能向我解释一下吗?

I know an infinite loop to the unintended kind usually causes a high CPU usage. But, I don't quite understand why. Can anyone explain that to me?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(4

断爱 2024-09-08 23:02:22

CPU 在执行该循环(永远不会结束)时无法执行任何其他操作。即使您使用的是抢占式多任务系统(这样无限循环只会永远阻塞它自己的进程或线程),每次操作系统的抢占式调度程序将循环交给它时,循环都会“吃掉”它的时间片。下一个切片的 CPU——什么都不做,但每次都会消耗一个切片的 CPU 时间,因此大量的 CPU 被所有其他线程占用,否则这些线程可以做有用的工作。

The CPU cannot do anything else while it's executing that loop (which never ends). Even if you're using a pre-emptive multi-tasking system (so that infinite loop will only clog forever its own process or thread), the loop will "eat" its time slice each time the OS's pre-emptive scheduler hands it the CPU for the next slice -- doing nothing, but eating up one slice's worth of CPU time each and every time, so that much CPU is lost to all other threads which could otherwise be doing useful work.

泅人 2024-09-08 23:02:22

无限循环与任何其他运行的代码没有什么不同。计算机不知道无限循环并不是一个复杂的计算,只是需要大量的迭代。

除非无限循环包含调用某些系统函数的代码,从而为操作系统提供时间,否则操作系统会将其视为正在积极处理某事的进程,并为其提供执行时间。如果没有其他进程在运行,它将占用 100% 的 CPU(在单核系统上)。

Infinite loops are no different than any other code running. The computer doesn't know that the infinite loop isn't a complicated calculation that just requires a lot of iterations.

Unless the infinite loop contains code that calls some system functions that yield time back to the OS, the OS treats it as a process that is actively working on something and gives it time to execute. If no other processes are running, it will eat up 100% of the CPU (on a single core system).

青衫儰鉨ミ守葔 2024-09-08 23:02:22

无限循环本身根本不是问题。大多数与用户交互的应用程序都是无限循环。他们反复等待用户,对其采取行动,然后再次执行循环。操作系统本身就是一个无限循环。这些类型的无限循环被认为是“高效的”,因为尽管无限地重复某些内容,但它们会定期输出对用户有用的内容。

我猜你担心的是无效的无限循环。但很明显为什么这些是一个问题。它们具有生产循环的所有缺点(消耗功率、使用 CPU 时间等),但没有任何优点,即。他们不生产任何有用的东西。

Infinite loops in themselves aren't a problem at all. Most applications that interact with a user are infinite loops. They repeatedly wait for user, act on it, and perform the cycle again. The operating system itself is an infinite loop. These kinds of infinite loop are said to be 'productive' because despite repeating something indefinitely, they periodically output something useful to the user.

I guess your concern is with unproductive infinite loops. But it's clear why these are a problem. They have all of the disadvantages of productive loops (consume power, use CPU time and so on) with none of the advantages ie. they don't produce anything useful.

Hello爱情风 2024-09-08 23:02:22

您可能指的是停止并开火指令

You are probably referring to the Halt and Catch Fire instruction

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