File tree Expand file tree Collapse file tree 1 file changed +16
-6
lines changed
Expand file tree Collapse file tree 1 file changed +16
-6
lines changed Original file line number Diff line number Diff line change 11package dnc
22
33import (
4+ "sort"
45 "time"
56)
67
78var rateLimitEvents []int64
89
9- // IsAllowed solves the problem in O(1) time and O(n) space.
10+ // nanoSecond represents one second in nanoseconds.
11+ const nanoSecond = 1e9
12+
13+ // IsAllowed solves the problem in O(log n) time and O(n) space.
1014func IsAllowed (limitPerSecond int ) bool {
11- now := time .Now ().Unix ()
12- removeOldERateLimitEvents (now )
15+ now := time .Now ().UnixNano ()
16+ removeOldRateLimitEvents (now )
1317 if len (rateLimitEvents ) >= limitPerSecond {
1418 return false
1519 }
@@ -18,10 +22,16 @@ func IsAllowed(limitPerSecond int) bool {
1822 return true
1923}
2024
21- func removeOldERateLimitEvents (now int64 ) {
22- if len (rateLimitEvents ) == 0 || now <= rateLimitEvents [0 ] {
25+ // removeOldRateLimitEvents uses binary search to remove events older than 1 second.
26+ func removeOldRateLimitEvents (now int64 ) {
27+ if len (rateLimitEvents ) == 0 {
2328 return
2429 }
2530
26- rateLimitEvents = []int64 {}
31+ cutoff := now - nanoSecond
32+ idx := sort .Search (len (rateLimitEvents ), func (i int ) bool {
33+ return rateLimitEvents [i ] >= cutoff
34+ })
35+
36+ rateLimitEvents = rateLimitEvents [idx :]
2737}
You can’t perform that action at this time.
0 commit comments