Skip to content

Commit

Permalink
Add benchmarks for ratelimiter
Browse files Browse the repository at this point in the history
  • Loading branch information
Narasimha1997 authored and Prasanna19971124 committed Oct 31, 2022
1 parent 9f75644 commit dd9f39c
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -440,6 +440,26 @@ go tool cover -html=c.out -o coverage.html

This will generate a file called `coverage.html`. The `coverage.html` is provided in the repo which is pre-generated.

**Benchmarks**:
Benchmarks can be executed by running:
```
go test -bench=.
```

Current benchmarks are as follows:
```
goos: linux
goarch: amd64
pkg: github.com/Narasimha1997/ratelimiter
cpu: Intel(R) Core(TM) i7-9750H CPU @ 2.60GHz
BenchmarkDefaultLimiter-12 11732958 85.61 ns/op
BenchmarkSyncLimiter-12 7047988 175.9 ns/op
BenchmarkConcurrentDefaultLimiter-12 7017625 163.9 ns/op
BenchmarkConcurrentSyncLimiter-12 4132976 256.3 ns/op
PASS
ok github.com/Narasimha1997/ratelimiter 46.408s
```

#### Notes on test:
The testing code produces 500 requests/sec with `2ms` precision time gap between each request. The accuracy of this `2ms` time tick generation can differ from platform to platform, even a small difference of 500 micorseconds can add up together and give more time for test to run in the end because of clock drift, as a result the error offset +/- 3 might not always work.
### Contributing
Expand Down
48 changes: 48 additions & 0 deletions limiter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -307,3 +307,51 @@ func TestSyncLimiterCleanup(t *testing.T) {
t.Fatalf("Calling ShouldAllow() on inactive limiter did not throw any errors.")
}
}

func BenchmarkDefaultLimiter(b *testing.B) {
limiter := NewDefaultLimiter(100, 1*time.Second)

for i := 0; i < b.N; i++ {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
}

func BenchmarkSyncLimiter(b *testing.B) {
limiter := NewSyncLimiter(100, 1*time.Second)

for i := 0; i < b.N; i++ {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
}

func BenchmarkConcurrentDefaultLimiter(b *testing.B) {
limiter := NewDefaultLimiter(100, 1*time.Second)

b.RunParallel(func(p *testing.PB) {
for p.Next() {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
})
}

func BenchmarkConcurrentSyncLimiter(b *testing.B) {
limiter := NewSyncLimiter(100, 1*time.Second)

b.RunParallel(func(p *testing.PB) {
for p.Next() {
_, err := limiter.ShouldAllow(1)
if err != nil {
b.Fatalf("Error when calling ShouldAllow() on active limiter, Error: %v", err)
}
}
})
}

0 comments on commit dd9f39c

Please sign in to comment.