Skip to content

Commit

Permalink
refactor(gateway): reuse 'now' instant for poll_acquire (#2393)
Browse files Browse the repository at this point in the history
We're always calling `clock_gettime()` when acquiring a permit even if
we've just done so already in when checking readiness. This is not a big
deal performance wise, but it feels counterintuitive to not reuse
already fetched resources as if the alrorithm required it (it does not).
  • Loading branch information
vilgotf authored Dec 7, 2024
1 parent beedad3 commit 2099918
Showing 1 changed file with 6 additions and 6 deletions.
12 changes: 6 additions & 6 deletions twilight-gateway/src/ratelimiter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,8 +81,8 @@ impl CommandRatelimiter {
/// * `Poll::Pending` if the ratelimiter is full
/// * `Poll::Ready` if a permit was granted.
pub(crate) fn poll_acquire(&mut self, cx: &mut Context<'_>) -> Poll<()> {
ready!(self.poll_ready(cx));
self.instants.push(Instant::now() + PERIOD);
let now = ready!(self.poll_ready(cx)).unwrap_or_else(Instant::now);
self.instants.push(now + PERIOD);

Poll::Ready(())
}
Expand All @@ -94,10 +94,10 @@ impl CommandRatelimiter {
/// The function returns:
///
/// * `Poll::Pending` if the ratelimiter is full
/// * `Poll::Ready` if the ratelimiter has spare capacity.
pub(crate) fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<()> {
/// * `Poll::Ready<Option(now)>` if the ratelimiter has spare capacity.
pub(crate) fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Option<Instant>> {
if self.instants.len() != self.instants.capacity() {
return Poll::Ready(());
return Poll::Ready(None);
}

if !self.delay.is_elapsed() {
Expand All @@ -119,7 +119,7 @@ impl CommandRatelimiter {
self.instants.rotate_right(used_permits);
self.instants.truncate(used_permits);

Poll::Ready(())
Poll::Ready(Some(now))
}
}
}
Expand Down

0 comments on commit 2099918

Please sign in to comment.