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

作者 : admin 本文共1124个字,预计阅读时间需要3分钟 发布时间: 2024-06-4 共4人阅读

说明

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 main

import (
	"flag"
	"fmt"
	"runtime"
	"time"
)

func burnCPU(percent int) {

	if 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
", numCPU)

	percent := flag.Int("p", 0, "CPU usage percentage (0-100)")
	flag.Parse()

	if *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
", *percent)

	// Create a goroutine for each CPU
	for i := 0; i < numCPU; i++ {
		go burnCPU(*percent)
	}

	// Prevent the main function from exiting
	select {}
}

本站无任何商业行为
个人在线分享 » Go 实现的命令行程序,可以通过参数来控制和消耗 CPU 占比。通常用于测试系统负载和性能。
E-->