欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 文旅 > 手游 > Go 实现的命令行程序,可以通过参数来控制和消耗 CPU 占比。通常用于测试系统负载和性能。

Go 实现的命令行程序,可以通过参数来控制和消耗 CPU 占比。通常用于测试系统负载和性能。

2025/2/24 6:14:51 来源:https://blog.csdn.net/weilaozongge/article/details/139447925  浏览:    关键词:Go 实现的命令行程序,可以通过参数来控制和消耗 CPU 占比。通常用于测试系统负载和性能。

说明

Go 实现的命令行程序,可以通过参数来控制和消耗 CPU 占比。通常用于测试系统负载和性能。
代码在下面

编译和运行

  1. 在终端中编译代码:

    go build 
    
  2. 运行程序并传入 CPU 使用率参数,例如:

    ./tools_cpu_burner -p=50
    

代码解释

  • flag.Int:用于定义一个命令行参数,该参数用于指定 CPU 使用率。
  • runtime.GOMAXPROCS:设置最大可同时使用的 CPU 数。
  • burnCPU:通过控制忙碌和空闲时间的比例来模拟 CPU 使用率。
  • Goroutines:程序为每个 CPU 启动一个 Goroutine,使每个 Goroutine 模拟相同的 CPU 使用率。
  • select{}:阻止主 Goroutine 退出,从而使其他 Goroutines 继续运行。

这样,就可以使用这个程序来测试不同的 CPU 使用情况,通过参数控制 CPU 占比。

上代码

package mainimport ("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.MillisecondidleTime := time.Duration(100-percent) * time.Millisecondfor {start := time.Now()// Busy loopfor time.Since(start) < busyTime {}// Idle timetime.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 CPUfor i := 0; i < numCPU; i++ {go burnCPU(*percent)}// Prevent the main function from exitingselect {}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词