Skip to content

Instantly share code, notes, and snippets.

@soul9
Created January 2, 2011 19:16
Show Gist options
  • Save soul9/762747 to your computer and use it in GitHub Desktop.
Save soul9/762747 to your computer and use it in GitHub Desktop.
time package problem
include $(GOROOT)/src/Make.inc
TARG=testtickers
GOFILES=testtickers.go
include $(GOROOT)/src/Make.cmd
package main
import (
"time"
"os"
"fmt"
"rand"
)
const (
second = 1000*1000*1000
minute = second * 60
maxtick = second*10
mintick = second/2
)
func newticktime() int64 {
t := rand.Int63n(maxtick)
for t < mintick {
t = rand.Int63n(maxtick)
}
return t
}
func startticker(t int64, done chan bool) {
ticker := time.NewTicker(t)
next := time.Nanoseconds() + t
fmt.Printf("Ticker of %f seconds at %s\n", float(t)/second, time.LocalTime().String())
<-ticker.C
diff := time.Nanoseconds()-next
fmt.Printf("Ticker of %f seconds, skew of %f at %s\n", float(t)/second, float(diff)/second, time.LocalTime().String())
if diff > second * 5 {
fmt.Printf("Fatal: skew of more than 5 seconds: %f\n", float(diff)/second)
os.Exit(1)
}
ticker.Stop()
time.Sleep(newticktime())
done <-true
return
}
func main() {
rand.Seed(time.Nanoseconds())
parallel := 4
numtests := 500
done := make(chan bool, parallel)
go func() {
ch := time.Tick(minute*15)
fmt.Printf("Ticker of %d seconds at %s\n", (minute*15)/second, time.LocalTime().String())
ch2 := time.Tick(minute)
fmt.Printf("Ticker of %d seconds at %s\n", minute/second, time.LocalTime().String())
for {
next := time.Nanoseconds() + minute*15
next2 := time.Nanoseconds() + minute
select {
case <-ch:
diff := time.Nanoseconds() - next
fmt.Printf("Ticker of %f seconds, skew of %f at %s\n", float(minute*15)/second, float(diff)/second, time.LocalTime().String())
break
case <-ch2:
diff := time.Nanoseconds() - next2
fmt.Printf("Ticker of %f seconds, skew of %f at %s\n", float(minute)/second, float(diff)/second, time.LocalTime().String())
break
}
}
}()
for i:=0; i<=parallel; i++ {
go startticker(newticktime(), done)
}
for i:=0; i<=numtests-parallel; i++ {
<-done
go startticker(newticktime(), done)
}
for i:=0; i<=parallel; i++ {
<-done
}
os.Exit(0)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment