如何降低计算密集线程的 CPU 占用率?

2020-01-20 09:25:58 +08:00
 ybw

在系统的默认调度策略下,这个线程会占满一个核心,直到它做完工作。

有没有办法让这个线程的 CPU 占用率始终保持在某个数值之下,比如不得超过 60%。

4313 次点击
所在节点    程序员
38 条回复
star00
2020-01-20 11:08:09 +08:00
为什么要限制 cpu,cpu 不够加机器啊
ybw
2020-01-20 11:08:57 +08:00
@happy7902 我就是想让剩下的 40 空闲,以便其他程序使用。
wangyzj
2020-01-20 11:09:20 +08:00
@ybw 多核的话你得代码层面拆分线程也许能做得到
star00
2020-01-20 11:19:02 +08:00
“线程会占满一个核心,直到它做完工作” ? 对这句话有点疑问。 现在的操作系统执行任务不是分时间片的吗? 如果有多个线程。一个线程执行一个时间片后,它们不会重新争夺 cpu 吗? 为什么这个线程会占满一个核心,直到它做完工作。 我也不太懂,只是有点疑问。
ybw
2020-01-20 11:20:24 +08:00
@star00 这只是我对实际观察到的现象的描述。
ddup
2020-01-20 11:21:24 +08:00
Thread.Sleep(1000)
sagaxu
2020-01-20 11:23:23 +08:00
第一句话就是错的,CPU 密集型线程,在调度时会受到一定惩罚,实际优先级低于同静态优先级的 IO 密集型线程。其它线程不但有机会运行,还更优先。
pmispig
2020-01-20 11:31:47 +08:00
搞个 docker 就行了
ybw
2020-01-20 11:34:42 +08:00
@sagaxu 不多说了,cpux.net
lambdaq
2020-01-20 11:38:10 +08:00
买主频更高的 cpu ?
opengps
2020-01-20 11:40:15 +08:00
sleep(10),让出 10 毫秒间隔
cigarzh
2020-01-20 11:47:48 +08:00
“在系统的默认调度策略下,这个线程会占满一个核心,直到它做完工作。”

哪个 OS 的啥 Scheduler 这么傻逼?
augustheart
2020-01-20 12:18:00 +08:00
@sagaxu 至少从 windows 的内核来说,是没有这个说法的。
sagaxu
2020-01-20 12:33:51 +08:00
@augustheart Windows NT-based operating systems use a multilevel feedback queue. 32 priority levels are defined, 0 through to 31, with priorities 0 through 15 being "normal" priorities and priorities 16 through 31 being soft real-time priorities, requiring privileges to assign. 0 is reserved for the Operating System. Users can select 5 of these priorities to assign to a running application from the Task Manager application, or through thread management APIs. The kernel may change the priority level of a thread depending on its I/O and CPU usage and whether it is interactive (i.e. accepts and responds to input from humans), raising the priority of interactive and I/O bounded processes and lowering that of CPU bound processes, to increase the responsiveness of interactive applications.[9] The scheduler was modified in Windows Vista to use the cycle counter register of modern processors to keep track of exactly how many CPU cycles a thread has executed, rather than just using an interval-timer interrupt routine.[10] Vista also uses a priority scheduler for the I/O queue so that disk defragmenters and other such programs do not interfere with foreground operations.
windyland
2020-01-20 13:09:19 +08:00
实际上调低优先级就可以了
augustheart
2020-01-20 14:06:24 +08:00
@sagaxu 这个说法我倒是没注意到。我推敲一下。
无论核心编程还是深入解析我好像都没有看到过有提到会特意将 cpu 密集型降低优先级的说法(实际上在我看来这个也无从判断,只能通过时间片的占用情况才能判断)。我再翻翻书,也可能我跳过了某句话。
BB9z
2020-01-20 22:17:05 +08:00
应用限制?比如 App Tamer、AppPolice。
zado
2020-01-20 23:24:26 +08:00
调低优先级就可以了,强行控制 CPU 占有率可以做到,如果想要控制精确一点还非常复杂,费力不讨好。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/639344

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX