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), "
")
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:
}
`