Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

perf: reduce copying in enforceSwarmPeerLimit() #5731

Merged
merged 2 commits into from
Jul 5, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
23 changes: 17 additions & 6 deletions libtransmission/peer-mgr.cc
Original file line number Diff line number Diff line change
Expand Up @@ -2054,7 +2054,12 @@ constexpr struct
{
return compare(a, b) < 0;
}
} ComparePeerByActivity{};
} ComparePeerByMostActive{};

constexpr auto ComparePeerByLeastActive = [](tr_peer const* a, tr_peer const* b)
{
return ComparePeerByMostActive(b, a);
};

[[nodiscard]] auto getPeersToClose(tr_swarm const* const swarm, time_t const now_sec)
{
Expand Down Expand Up @@ -2085,15 +2090,21 @@ void closeBadPeers(tr_swarm* s, time_t const now_sec)
void enforceSwarmPeerLimit(tr_swarm* swarm, size_t max)
{
// do we have too many peers?
if (auto const n = swarm->peerCount(); n <= max)
auto const n = swarm->peerCount();
if (n <= max)
{
return;
}

// close all but the `max` most active
auto peers = swarm->peers;
std::partial_sort(std::begin(peers), std::begin(peers) + max, std::end(peers), ComparePeerByActivity);
std::for_each(std::begin(peers) + max, std::end(peers), closePeer);
auto peers = std::vector<tr_peerMsgs*>{ n - max };
std::partial_sort_copy(
std::begin(swarm->peers),
std::end(swarm->peers),
std::begin(peers),
std::end(peers),
ComparePeerByLeastActive);
std::for_each(std::begin(peers), std::end(peers), closePeer);
}

void enforceSessionPeerLimit(tr_session* session)
Expand All @@ -2116,7 +2127,7 @@ void enforceSessionPeerLimit(tr_session* session)
TR_ASSERT(tr_peerMsgs::size() == std::size(peers));
if (std::size(peers) > max)
{
std::partial_sort(std::begin(peers), std::begin(peers) + max, std::end(peers), ComparePeerByActivity);
std::partial_sort(std::begin(peers), std::begin(peers) + max, std::end(peers), ComparePeerByMostActive);
std::for_each(std::begin(peers) + max, std::end(peers), closePeer);
}
}
Expand Down