为什么Windows和macOS/Linux的sleep(1)的CPU使用率会有很大差异?
我观察到while true sleep(1)Windows 和 macOS/Linux 之间的 CPU 使用率差异很大。
Linux/macOS:下面的代码会导致 CPU 过高,甚至在top. (我的 CPU 有 4 个内核,所以总内核数top是 400%。)
Windows:令我惊讶的是,它在 Windows 任务管理器中只显示 0% 的 CPU 使用率。
那么……原因是什么?
代码有 Java 和 C# 版本;它们显示出相似的结果。
爪哇
/**
* Platform=openjdk 11, test in CentOS7.5/macOS11/Windows7
*/
public class Test {
public static void main(String[] args) throws Exception {
for (Integer i = 0; i < 100; i++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
Thread.sleep(1);
}
}
catch (Exception ex){
ex.printStackTrace();
}
}
});
thread.start();
if(i == 100)
thread.join();
}
}
}
C#
/**
* sdk=NET5, test in CentOS7.5/macOS11/Windows7
*/
class Program
{
static void Main(string[] args)
{
var threadList = new List<Thread>(100);
foreach (var index in Enumerable.Range(1, 100))
{
var thread = new Thread(() =>
{
while (true)
{
Thread.Sleep(1);
}
});
thread.Start();
threadList.Add(thread);
}
threadList[0].Join();
}
}
2021.5.8
我已经实现了这个演示的 goroutine 版本,它在 CentOS7 上只使用了不到 5% 的 CPU 使用率。那么我可以认为CPU使用率被Linux LWP的上下文切换消耗了吗?
走
package main
import (
"runtime"
"sync"
"time"
)
var wg sync.WaitGroup
func main() {
for i := 0; i < 100; i++ {
go sleep()
}
runtime.Gosched()
wg.Add(1)
wg.Wait()
}
func sleep() {
for {
time.Sleep(time.Millisecond)
}
}
THE END
二维码