Created
April 17, 2014 15:21
-
-
Save menghan/10991560 to your computer and use it in GitHub Desktop.
consume cpu at specified percent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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