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 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 {}
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

^_^ 纵歌

工作中的经验分享

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值