Go 实现的命令行程序,可以通过参数来控制和消耗 CPU 占比。通常用于测试系统负载和性能。
代码在下面
在终端中编译代码:
go build
运行程序并传入 CPU 使用率参数,例如:
./tools_cpu_burner -p=50
这样,就可以使用这个程序来测试不同的 CPU 使用情况,通过参数控制 CPU 占比。
package main
import (
"flag"
"fmt"
"runtime"
"time"
)
func burnCPU(percent int) {
if percent < 0 || percent > 100 {
fmt.Println("CPU usage percent must be between 0 and 100")
return
}
busyTime := time.Duration(percent) * time.Millisecond
idleTime := time.Duration(100-percent) * time.Millisecond
for {
start := time.Now()
// Busy loop
for time.Since(start) < busyTime {
}
// Idle time
time.Sleep(idleTime)
}
}
func main() {
numCPU := runtime.NumCPU()
runtime.GOMAXPROCS(numCPU)
fmt.Printf("Using %d CPUs\n", numCPU)
percent := flag.Int("p", 0, "CPU usage percentage (0-100)")
flag.Parse()
if *percent <= 0 || *percent > 100 {
fmt.Println("CPU usage percent must be between 0 and 100")
fmt.Println("Usage: ./tools_cpu_burner -p=20 ")
return
}
fmt.Printf("Burning CPU at %d%% usage\n", *percent)
// Create a goroutine for each CPU
for i := 0; i < numCPU; i++ {
go burnCPU(*percent)
}
// Prevent the main function from exiting
select {}
}