Skip to content

Commit

Permalink
Use std::unordered_set instead of std::vector in IsEvicted()
Browse files Browse the repository at this point in the history
Summary:
An unordered set can tell if an element is present in ~O(1) time (constant on
average, worst case linear to the size of the container), which speeds up and
simplifies the lookup in IsEvicted().

Co-authored-by: Vasil Dimov <vd@FreeBSD.org>

This is a backport of [[bitcoin/bitcoin#20197 | core#20197]] [3/6]
bitcoin/bitcoin@ca63b53
Depends on D10976

Test Plan: `ninja check`

Reviewers: #bitcoin_abc, Fabien

Reviewed By: #bitcoin_abc, Fabien

Differential Revision: https://reviews.bitcoinabc.org/D10977
  • Loading branch information
jonatack authored and PiRK committed Feb 4, 2022
1 parent e17e1b2 commit 7128106
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions src/test/net_peer_eviction_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
#include <functional>
#include <numeric>
#include <optional>
#include <unordered_set>
#include <vector>

BOOST_FIXTURE_TEST_SUITE(net_peer_eviction_tests, BasicTestingSetup)
Expand Down Expand Up @@ -45,24 +46,23 @@ GetRandomNodeEvictionCandidates(const int n_candidates,

// Returns true if any of the node ids in node_ids are selected for eviction.
bool IsEvicted(std::vector<NodeEvictionCandidate> candidates,
const std::vector<NodeId> &node_ids,
const std::unordered_set<NodeId> &node_ids,
FastRandomContext &random_context) {
Shuffle(candidates.begin(), candidates.end(), random_context);
const std::optional<NodeId> evicted_node_id =
SelectNodeToEvict(std::move(candidates));
if (!evicted_node_id) {
return false;
}
return std::find(node_ids.begin(), node_ids.end(), *evicted_node_id) !=
node_ids.end();
return node_ids.count(*evicted_node_id);
}

// Create number_of_nodes random nodes, apply setup function candidate_setup_fn,
// apply eviction logic and then return true if any of the node ids in node_ids
// are selected for eviction.
bool IsEvicted(const int number_of_nodes,
std::function<void(NodeEvictionCandidate &)> candidate_setup_fn,
const std::vector<NodeId> &node_ids,
const std::unordered_set<NodeId> &node_ids,
FastRandomContext &random_context) {
std::vector<NodeEvictionCandidate> candidates =
GetRandomNodeEvictionCandidates(number_of_nodes, random_context);
Expand Down Expand Up @@ -185,7 +185,9 @@ BOOST_AUTO_TEST_CASE(node_eviction_test) {
candidate.availabilityScore =
double(number_of_nodes - candidate.id);
},
protectedNodes, random_context));
std::unordered_set(protectedNodes.begin(),
protectedNodes.end()),
random_context));

// An eviction is expected given >= 161 random eviction candidates.
// The eviction logic protects at most four peers by net group,
Expand Down

0 comments on commit 7128106

Please sign in to comment.