|
| 1 | +package pebble |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "testing" |
| 6 | + "time" |
| 7 | + |
| 8 | + "github.com/stretchr/testify/require" |
| 9 | +) |
| 10 | + |
| 11 | +func TestSmootherOff(t *testing.T) { |
| 12 | + smoother := Smoother{enabled: false} |
| 13 | + smoother.mu.estimatedUtilization = 0.5 |
| 14 | + smoother.startWork() |
| 15 | + sleepTime := smoother.finishWork(time.Duration(100), false) |
| 16 | + require.Equal(t, time.Duration(0), sleepTime) |
| 17 | +} |
| 18 | + |
| 19 | +func TestSleepConverge(t *testing.T) { |
| 20 | + smoother := Smoother{enabled: true} |
| 21 | + for x := 0; x < 100; x++ { |
| 22 | + smoother.startWork() |
| 23 | + smoother.finishWork(time.Duration(x)*time.Millisecond, false) |
| 24 | + } |
| 25 | + sleepTime := smoother.finishWork(100*time.Millisecond, false) |
| 26 | + // This is ~91 because it converges to recent measurements |
| 27 | + require.InDelta(t, 91*time.Millisecond, sleepTime, float64(10*time.Microsecond)) |
| 28 | +} |
| 29 | + |
| 30 | +func TestMultipleRunners(t *testing.T) { |
| 31 | + smoother := Smoother{enabled: true} |
| 32 | + smoother.start() |
| 33 | + smoother.mu.estimatedUtilization = 1 |
| 34 | + for i := 0; i < 11; i++ { |
| 35 | + for j := 0; j < 10; j++ { |
| 36 | + smoother.startWork() |
| 37 | + } |
| 38 | + time.Sleep(102 * time.Millisecond) |
| 39 | + for j := 0; j < 10; j++ { |
| 40 | + smoother.finishWork(0, true) |
| 41 | + } |
| 42 | + } |
| 43 | + smoother.stop() |
| 44 | + fmt.Println(smoother.mu.estimatedUtilization) |
| 45 | + // The estimate should be about 10% closer to 10 starting at 1.0. |
| 46 | + require.InDelta(t, 1.9, smoother.mu.estimatedUtilization, 0.001) |
| 47 | +} |
| 48 | + |
| 49 | +func TestSleep(t *testing.T) { |
| 50 | + smoother := Smoother{enabled: true} |
| 51 | + smoother.mu.estimatedIterDurationNs = float64(10 * time.Millisecond) |
| 52 | + smoother.mu.estimatedUtilization = 0.5 |
| 53 | + |
| 54 | + smoother.startWork() |
| 55 | + smoother.finishWork(1*time.Millisecond, true) |
| 56 | + |
| 57 | + require.Equal(t, smoother.mu.estimatedUtilization, 0.5) |
| 58 | + require.InDelta(t, smoother.mu.estimatedIterDurationNs, float64(9*time.Millisecond), float64(time.Millisecond)) |
| 59 | +} |
| 60 | + |
| 61 | +func TestAvgUtil(t *testing.T) { |
| 62 | + smoother := Smoother{enabled: true} |
| 63 | + smoother.start() |
| 64 | + smoother.mu.estimatedUtilization = 0.5 |
| 65 | + for i := 0; i < 11; i++ { |
| 66 | + smoother.startWork() |
| 67 | + time.Sleep(102 * time.Millisecond) |
| 68 | + smoother.finishWork(0, false) |
| 69 | + time.Sleep(102 * time.Millisecond) |
| 70 | + } |
| 71 | + smoother.stop() |
| 72 | + // It should never be exactly 0.5, but should be close. This test has a |
| 73 | + // potential to randomly fail, so think about ways to fix it. |
| 74 | + require.InDelta(t, 0.5, smoother.mu.estimatedUtilization, 0.01) |
| 75 | +} |
0 commit comments