Not able to find out where in the below for loop we are spending more than ten microseconds so that we are missing vast number of ticks?
package main
import (
"context"
"fmt"
"time"
)
func main() {
RunTicker(time.Millisecond, 10 * time.Second) // Scenario 1
RunTicker(10 * time.Microsecond, 10 * time.Second) // Scenario 2
}
func RunTicker(tickerInterval, tickerDuration time.Duration) {
var counter int
ctx, can := context.WithTimeout(context.Background(), tickerDuration)
defer can()
ticker := time.NewTicker(tickerInterval)
exitfor:
for {
select {
case <-ticker.C:
counter++
case <- ctx.Done():
ticker.Stop()
break exitfor
}
}
fmt.Printf("Tick interval %v and running for %v.Expected counter: %d but got %d\n", tickerInterval, tickerDuration, tickerDuration/tickerInterval, counter)
}
Output:
Tick interval 1ms and running for 10s.Expected counter: 10000 but got 9965
Tick interval 10µs and running for 10s.Expected counter: 1000000 but got 976590