rate

package module
v1.8.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: May 8, 2024 License: MIT Imports: 3 Imported by: 1

README

build coverage goreport Docs

An efficient rate limiter for Go

Because too much of the CPU consumed was golang.org/x/time/rate.Limiter.Wait() calling time.Now().

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Limiter

type Limiter struct {
	// contains filtered or unexported fields
}

Limiter provides efficient rate limiting. The zero value is immediately usable.

A Limiter is not safe to use from multiple goroutines simultaneously.

func (*Limiter) Wait

func (rl *Limiter) Wait(maxrate *int32) (rate int32)

Wait sleeps at least long enough to ensure that Wait cannot be called more than `*maxrate` times per second.

Returns the current rate, or zero if currently unlimited.

A nil `maxrate` or a `*maxrate` of zero or less doesn't wait at all.

type Ticker added in v1.3.0

type Ticker struct {
	C <-chan struct{} // sends a struct{}{} at most maxrate times per second
	// contains filtered or unexported fields
}

func NewTicker

func NewTicker(parent <-chan struct{}, maxrate *int32) *Ticker

NewTicker returns a Ticker that reads ticks from a parent channel and sends a `struct{}{}` at most `*maxrate` times per second.

The effective max rate is thus the lower of the parent channels rate of sending and `*maxrate`.

A nil `parent` channel means tick rate is only limited by `maxrate`. A non-nil parent channel that closes will cause this Ticker to stop sending ticks.

A nil `maxrate` or a `*maxrate` of zero or less sends as quickly as possible, so only limited by the parent channel.

func (*Ticker) Close added in v1.3.0

func (ticker *Ticker) Close()

Close stops the Ticker and frees resources.

It is safe to call multiple times or concurrently. Once Close() returns, no more ticks will be delivered, and if you passed a non-nil ticker counter to NewTicker(), it will be correct.

func (*Ticker) Count added in v1.8.0

func (ticker *Ticker) Count() (n int64)

Count returns the number of ticks delivered so far.

func (*Ticker) Load added in v1.8.0

func (ticker *Ticker) Load() (n int32)

Load returns the current load in permille.

func (*Ticker) Rate added in v1.8.0

func (ticker *Ticker) Rate() (n int32)

Rate returns the current rate of ticks per second.

func (*Ticker) Wait added in v1.5.0

func (ticker *Ticker) Wait()

Wait delays until the next tick is available, then adds a "free tick" back to the Ticker.

Typical use case is to launch goroutines that in turn uses the Ticker to rate limit some resource or action, thus limiting the rate of goroutines spawning without impacting the resource use rate.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL