Skip to content

Instantly share code, notes, and snippets.

@menghan
Created April 17, 2014 15:21
Show Gist options
  • Save menghan/10991560 to your computer and use it in GitHub Desktop.
Save menghan/10991560 to your computer and use it in GitHub Desktop.
consume cpu at specified percent
package main
import (
"flag"
"log"
"runtime"
"strconv"
"time"
)
func loop(c <-chan bool) {
_, ok := <-c // start
if !ok {
return
}
i := 0 // to work under go1.1.2
for {
select {
case _, ok = <-c:
if !ok {
return
}
_, ok = <-c
if !ok {
return
}
default:
// to work under go1.1.2
i++
if i % 10000 == 0 {
runtime.Gosched()
i = 0
}
}
}
}
func main() {
flag.Parse()
percent, err := strconv.Atoi(flag.Arg(0))
if err != nil {
log.Fatal(err)
}
c := make(chan bool)
go loop(c)
unit := int(time.Second)
for {
c <- true
time.Sleep(time.Duration(unit * percent / 100))
c <- true
time.Sleep(time.Duration(unit * (100 - percent) / 100))
}
close(c)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment