我已经编写了代码来获取CPU内核的使用百分比。如果一个内核的 CPU 使用率低于 50%,我将运行压力测试代码,以将使用率百分比提高到高于 50%。我必须为所有CPU内核应用此策略。
这是我的完整代码:
package main
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"strconv"
"strings"
"time"
"github.com/dhoomakethu/stress/utils"
strip "github.com/grokify/html-strip-tags-go"
)
func main() {
url := "http://localhost:8080/getCPU"
resp := Get(url)
//remove htlm tag
stripped := strip.StripTags(resp)
s := strings.Split(stripped, "%")
var j []int
for i := 0; i < len(s)-1; i++ {
number, _ := strconv.Atoi(s[i])
if number < 50 {
j = append(j, i)
}
}
fmt.Println(j)
sampleInterval := 100 * time.Millisecond
cpuload := 1.0
duration := 300.0
for a := 0; a < len(j)/2; a++ {
cpucore := j[a]
runCpuLoader(sampleInterval, cpuload, duration, cpucore)
}
}
//GET
func Get(url string) string {
response, err := http.Get(url)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
} else {
defer response.Body.Close()
contents, err := ioutil.ReadAll(response.Body)
if err != nil {
fmt.Printf("%s", err)
os.Exit(1)
}
return string(contents)
}
return ""
}
// stress cpu
func runCpuLoader(sampleInterval time.Duration, cpuload float64, duration float64, cpu int) {
controller := utils.NewCpuLoadController(sampleInterval, cpuload)
monitor := utils.NewCpuLoadMonitor(float64(cpu), sampleInterval)
actuator := utils.NewCpuLoadGenerator(controller, monitor, time.Duration(duration))
utils.StartCpuLoadController(controller)
utils.StartCpuMonitor(monitor)
utils.RunCpuLoader(actuator)
utils.StopCpuLoadController(controller)
utils.StopCpuMonitor(monitor)
}
在这段代码中
for a := 0; a < len(j)/2; a++ {
cpucore := j[a]
runCpuLoader(sampleInterval, cpuload, duration, cpucore)
}
}
我希望代码并发运行压力测试增加 CPU 使用率的百分比。但该函数的持续时间为 5 分钟,因此它不能作为并发运行。runCpuLoader(sampleInterval, cpuload, duration, cpucore)
德玛西亚99
相关分类