Skip to content

Commit

Permalink
Avoid unnecessary timers.
Browse files Browse the repository at this point in the history
Avoid unnecessarily adding libevent timers.

This reduces CPU utilization during a download
bandwidth test by ~11%.
  • Loading branch information
jellefoks committed Oct 15, 2024
1 parent 95e0b1c commit 8fb9f95
Showing 1 changed file with 19 additions and 12 deletions.
31 changes: 19 additions & 12 deletions starboard/shared/libevent/socket_waiter_internal.cc
Original file line number Diff line number Diff line change
Expand Up @@ -271,31 +271,38 @@ void SbSocketWaiterPrivate::Wait() {
SbSocketWaiterResult SbSocketWaiterPrivate::WaitTimed(int64_t duration_usec) {
SB_DCHECK(pthread_equal(pthread_self(), thread_));

if ((duration_usec == 0) || (duration_usec == kSbInt64Max)) {
// There is no need for a timeout event in these cases.
event_base_loop(base_,
(duration_usec == 0) ? EVLOOP_ONCE | EVLOOP_NONBLOCK : 0);

SbSocketWaiterResult result = woken_up_ ? kSbSocketWaiterResultWokenUp
: kSbSocketWaiterResultTimedOut;
woken_up_ = false;

return result;
}

// The way to do this is apparently to create a timeout event, call WakeUp
// inside that callback, and then just do a normal wait.
struct event event;
timeout_set(&event, &SbSocketWaiterPrivate::LibeventTimeoutCallback, this);
event_base_set(base_, &event);

if (duration_usec < kSbInt64Max) {
struct timeval tv;
tv.tv_sec = duration_usec / 1'000'000;
tv.tv_usec = duration_usec % 1'000'000;
timeout_add(&event, &tv);
}
struct timeval tv;
tv.tv_sec = duration_usec / 1'000'000;
tv.tv_usec = duration_usec % 1'000'000;
timeout_add(&event, &tv);

event_base_loop(base_, 0);

SbSocketWaiterResult result =
woken_up_ ? kSbSocketWaiterResultWokenUp : kSbSocketWaiterResultTimedOut;
woken_up_ = false;

if (duration_usec < kSbInt64Max) {
// We clean this up, in case we were awakened early, to prevent a spurious
// wake-up later.
timeout_del(&event);
}

// We clean this up, in case we were awakened early, to prevent a spurious
// wake-up later.
timeout_del(&event);
return result;
}

Expand Down

0 comments on commit 8fb9f95

Please sign in to comment.