Skip to content

Instantly share code, notes, and snippets.

@prashantv
Last active November 15, 2023 10:18
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save prashantv/26016a7dbc6fc1ec52d8c2b6591f3582 to your computer and use it in GitHub Desktop.
Save prashantv/26016a7dbc6fc1ec52d8c2b6591f3582 to your computer and use it in GitHub Desktop.

golang.org rate limiter:

	rl := rate.NewLimiter(1000000, 1)
 
	last := time.Now()
	for i := 0; i < 10; i++ {
		rl.Wait(context.Background())
		cur := time.Now()
		fmt.Println("last", cur.Sub(last))
		last = cur
	}

Output:

last 16.038µs
last 11.367µs
last 4.051µs
last 4.582µs
last 2.146µs
last 3.085µs
last 2.173µs
last 3.121µs
last 1.984µs
last 3.09µs

uber-go rate limiter:

	rl := ratelimit.New(1000000, ratelimit.WithoutSlack)

	last := time.Now()
	for i := 0; i < 10; i++ {
		rl.Take()
		cur := time.Now()
		fmt.Println("last", cur.Sub(last))
		last = cur
	}

Output:

last 315ns
last 1.846µs
last 1.3µs
last 1.218µs
last 1.191µs
last 1.202µs
last 1.206µs
last 1.216µs
last 1.166µs
last 1.18µs
@tgulacsi
Copy link

What about the context.Background() call? You're measuring that, too!

@prashantv
Copy link
Author

@tgulacsi context.Background returns a global variable, it doesn't really cost anything:
https://golang.org/src/context/context.go?s=7222:7247#L205

Just to confirm, I re-ran with the context.Backgroundout of the loop,

    ctx := context.Background()
    last := time.Now()
    for i := 0; i < 10; i++ {
        rl.Wait(ctx)
        cur := time.Now()
        fmt.Println("last", cur.Sub(last))
        last = cur
    }

And as expected, there's no performance difference:

last 19.098µs
last 9.628µs
last 4.207µs
last 2.839µs
last 2.767µs
last 2.619µs
last 4.12µs
last 2.977µs
last 3.946µs
last 2.535µs

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment