-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathcpu_load.go
42 lines (37 loc) · 990 Bytes
/
cpu_load.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
package main
import (
"runtime"
"time"
)
// RunCPULoad run CPU load in specify cores count and percentage
func RunCPULoad(coresCount int, timeSeconds int, percentage int) {
runtime.GOMAXPROCS(coresCount)
// second ,s * 1
// millisecond,ms * 1000
// microsecond,μs * 1000 * 1000
// nanosecond ,ns * 1000 * 1000 * 1000
// every loop : run + sleep = 1 unit
// 1 unit = 100 ms may be the best
unitHundresOfMicrosecond := 1000
runMicrosecond := unitHundresOfMicrosecond * percentage
sleepMicrosecond := unitHundresOfMicrosecond*100 - runMicrosecond
for i := 0; i < coresCount; i++ {
go func() {
runtime.LockOSThread()
// endless loop
for {
begin := time.Now()
for {
// run 100%
if time.Now().Sub(begin) > time.Duration(runMicrosecond)*time.Microsecond {
break
}
}
// sleep
time.Sleep(time.Duration(sleepMicrosecond) * time.Microsecond)
}
}()
}
// how long
time.Sleep(time.Duration(timeSeconds) * time.Second)
}