From 29ac3a290635dca862934a035e98e4ab3eb5f540 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82?= Date: Wed, 6 Jul 2022 20:39:15 -0700 Subject: [PATCH] Update example to include a withoutSlack option (#96) In #90 @twelsh-aw found a bug in a new implementation. This turned out to be caused by us mocking time. Since time mocking will always have some risks this diff proposes to expand the `examples` we're using - since they use "real" time they should be good enough to cover most basic cases like #90. In particular: - we add a "withoutSlack" test so that the exact case reported in #90 doesn't happen. No slack option seems common enough to add it. - updates "withSlack" example to actually show how slack operates. Due to non-even execution times I'm forced to round the time a bit. Possible issues: - test stability: I re-run the test a 1000 times without issues - the timing seems to be stable. - test duration: in total we're extending the examples by 5ms, which shouldn't be human noticeable. --- example_test.go | 35 +++++++++++++++++++++++++++++------ 1 file changed, 29 insertions(+), 6 deletions(-) diff --git a/example_test.go b/example_test.go index 31e509d..8162409 100644 --- a/example_test.go +++ b/example_test.go @@ -7,11 +7,38 @@ import ( "go.uber.org/ratelimit" ) -func Example() { - rl := ratelimit.New(100) // per second +func Example_default() { + rl := ratelimit.New(100) // per second, some slack. + + rl.Take() // Initialize. + time.Sleep(time.Millisecond * 45) // Let some time pass. prev := time.Now() for i := 0; i < 10; i++ { + now := rl.Take() + if i > 0 { + fmt.Println(i, now.Sub(prev).Round(time.Millisecond*2)) + } + prev = now + } + + // Output: + // 1 0s + // 2 0s + // 3 0s + // 4 4ms + // 5 10ms + // 6 10ms + // 7 10ms + // 8 10ms + // 9 10ms +} + +func Example_withoutSlack() { + rl := ratelimit.New(100, ratelimit.WithoutSlack) // per second, no slack. + + prev := time.Now() + for i := 0; i < 6; i++ { now := rl.Take() if i > 0 { fmt.Println(i, now.Sub(prev)) @@ -25,8 +52,4 @@ func Example() { // 3 10ms // 4 10ms // 5 10ms - // 6 10ms - // 7 10ms - // 8 10ms - // 9 10ms }