2008-12-03 17:40:00 -07:00
|
|
|
// Copyright 2009 The Go Authors. All rights reserved.
|
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
2009-08-12 14:18:37 -06:00
|
|
|
package time_test
|
2008-12-03 17:40:00 -07:00
|
|
|
|
|
|
|
import (
|
2009-12-15 16:41:46 -07:00
|
|
|
"testing"
|
|
|
|
. "time"
|
2008-12-03 17:40:00 -07:00
|
|
|
)
|
|
|
|
|
2009-09-23 14:02:14 -06:00
|
|
|
func TestTicker(t *testing.T) {
|
2008-12-03 17:40:00 -07:00
|
|
|
const (
|
2009-12-15 16:41:46 -07:00
|
|
|
Delta = 100 * 1e6
|
|
|
|
Count = 10
|
2009-10-07 12:55:06 -06:00
|
|
|
)
|
2009-12-15 16:41:46 -07:00
|
|
|
ticker := NewTicker(Delta)
|
|
|
|
t0 := Nanoseconds()
|
2008-12-03 17:40:00 -07:00
|
|
|
for i := 0; i < Count; i++ {
|
2009-11-09 13:07:39 -07:00
|
|
|
<-ticker.C
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
2009-12-15 16:41:46 -07:00
|
|
|
ticker.Stop()
|
|
|
|
t1 := Nanoseconds()
|
|
|
|
ns := t1 - t0
|
|
|
|
target := int64(Delta * Count)
|
|
|
|
slop := target * 2 / 10
|
2009-10-07 12:55:06 -06:00
|
|
|
if ns < target-slop || ns > target+slop {
|
2009-11-09 13:07:39 -07:00
|
|
|
t.Fatalf("%d ticks of %g ns took %g ns, expected %g", Count, float64(Delta), float64(ns), float64(target))
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
2009-09-23 14:02:14 -06:00
|
|
|
// Now test that the ticker stopped
|
2009-12-15 16:41:46 -07:00
|
|
|
Sleep(2 * Delta)
|
2011-01-31 16:36:28 -07:00
|
|
|
select {
|
|
|
|
case <-ticker.C:
|
2010-12-07 14:42:54 -07:00
|
|
|
t.Fatal("Ticker did not shut down")
|
2011-01-31 16:36:28 -07:00
|
|
|
default:
|
|
|
|
// ok
|
2009-09-23 14:02:14 -06:00
|
|
|
}
|
2008-12-03 17:40:00 -07:00
|
|
|
}
|
2010-02-17 15:55:29 -07:00
|
|
|
|
|
|
|
// Test that a bug tearing down a ticker has been fixed. This routine should not deadlock.
|
|
|
|
func TestTeardown(t *testing.T) {
|
|
|
|
for i := 0; i < 3; i++ {
|
|
|
|
ticker := NewTicker(1e8)
|
|
|
|
<-ticker.C
|
|
|
|
ticker.Stop()
|
|
|
|
}
|
|
|
|
}
|
2011-01-25 13:25:48 -07:00
|
|
|
|
|
|
|
func BenchmarkTicker(b *testing.B) {
|
|
|
|
ticker := NewTicker(1)
|
|
|
|
b.ResetTimer()
|
|
|
|
b.StartTimer()
|
|
|
|
for i := 0; i < b.N; i++ {
|
|
|
|
<-ticker.C
|
|
|
|
}
|
|
|
|
b.StopTimer()
|
|
|
|
ticker.Stop()
|
|
|
|
}
|