golang - CPU 使用量

发布时间:2022-07-03 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了golang - CPU 使用量脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

golang - CPU 使用量

./cpuLimit 0.35 (限制使用率35%,使用0.35 作为参数)

  • cpuLimit

` package main

import ( "fmt" "io/ioutil" // "math" "os" "runtime" "strconv" "strings" "time" )

func main() { cpuNum := runtime.NumCPU() // fmt.Println(os.Args) //limitPer := 0.35

limitPer, _ := strconv.ParseFloat(os.Args[1], 64)
fmt.Println("cpuNum: ", cpuNum)
var chArr []chan bool = make([]chan bool, cpuNum*4)
for i := 0; i < cpuNum*4; i++ {
	chArr[i] = make(chan bool)
}
tag := 0

for {
	idle0, total0 := getCPUSample()
	time.Sleep(3 * time.Second)
	idle1, total1 := getCPUSample()

	idleTicks := float64(idle1 - idle0)
	// fmt.Println("idleTicks: ", idleTicks)
	totalTicks := float64(total1 - total0)
	// fmt.Println("totalTicks: ", totalTicks)
	cpuUsage := (totalTicks - idleTicks) / totalTicks
	fmt.Println("cpuUsage: ", cpuUsage)
	// busyNum := int(math.Floor(cpuUsage * float64(cpuNum)))
	// busyNum := int(math.Floor(cpuUsage * float64(cpuNum)))
	// pointerNum := int(math.Floor(float64(cpuNum) * limitPer))
	// fmt.Println("busynum: ", busyNum)
	// fmt.Println("pointerNum: ", pointerNum)

	//busyNum := 3
	if tag > 0 && cpuUsage > limitPer {
		//for i := tag; i < tag; i-- {
		// fmt.Println("tag---: ", tag)
		chArr[tag-1] <- true
		tag -= 1
		//}
	} else if cpuUsage < limitPer {
		//for i := tag; i < pointerNum; i++ {
		// fmt.Println("tag++++: ", tag)
		go RunSomething(chArr[tag])
		tag += 1
		//}
	}
	time.Sleep(time.Duration(5) * time.Second)
	fmt.Println("now thread: ", tag)
	// fmt.Println(len(chArr))
}

}

func getCPUSample() (idle, total uint64) { contents, err := ioutil.ReadFile("/proc/stat") if err != nil { return } lines := strings.Split(string(contents), "n") for _, line := range lines { fields := strings.Fields(line) if fields[0] == "cpu" { numFields := len(fields) for i := 1; i < numFields; i++ { val, err := strconv.ParseUint(fields[i], 10, 64) if err != nil { fmt.Println("Error: ", i, fields[i], err) } total += val // tally up all the numbers to get total ticks if i == 4 { // idle is the 5th field in the cpu line idle = val } } return } } return }

func RunSomething(stopCh chan bool) { for { select { case ag := <-stopCh: fmt.Println(ag) goto end default: for j := 1; j < 100000; j++ { os.Hostname() } } // fmt.Println(".........") } end: }

`

脚本宝典总结

以上是脚本宝典为你收集整理的golang - CPU 使用量全部内容,希望文章能够帮你解决golang - CPU 使用量所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: