Skip to content

Instantly share code, notes, and snippets.

@wcp1231
Created May 17, 2021 09:43
Show Gist options
  • Save wcp1231/0997bdb7db0972f3d9143d76dd75fcc6 to your computer and use it in GitHub Desktop.
Save wcp1231/0997bdb7db0972f3d9143d76dd75fcc6 to your computer and use it in GitHub Desktop.
测试 CPU Throttling 的简单程序
package main
import (
"crypto/sha512"
"flag"
"log"
"syscall"
"time"
)
func main() {
sleep := flag.Duration("sleep", time.Second, "sleep between iterations")
iters := flag.Int("iter", 1, "work iters")
flag.Parse()
time.Sleep(time.Second)
prev := usage()
for {
s := time.Now()
burn(*iters)
e := time.Now().Sub(s)
curr := usage()
log.Printf("burn took %dms, cpu took %dms, cpu time so far: %dms",
ms(e), ms64(curr - prev), ms(time.Duration(curr)))
prev = curr
time.Sleep(*sleep)
}
}
func ms(duration time.Duration) int {
return ms64(duration.Nanoseconds())
}
func ms64(m int64) int {
return int(m / 1000 / 1000)
}
func burn(iters int) {
for i := 0; i < iters; i++ {
sum := sha512.New()
sum.Write([]byte("banana"))
sum.Sum([]byte{})
}
}
func usage() int64 {
r := syscall.Rusage{}
syscall.Getrusage(syscall.RUSAGE_SELF, &r)
return r.Stime.Nano() + r.Utime.Nano()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment