Skip to content

Commit

Permalink
Add timing test for two different msb algorithms
Browse files Browse the repository at this point in the history
  • Loading branch information
jamescowens committed Jan 28, 2024
1 parent 2c21474 commit cdf6b15
Showing 1 changed file with 63 additions and 0 deletions.
63 changes: 63 additions & 0 deletions src/test/gridcoin/sidestake_tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,71 @@
#include <util.h>
#include <gridcoin/sidestake.h>

namespace {
// This is the one currently used in the Fraction class
int msb(const int64_t& n)
{
// Log2 is O(1) both time and space-wise and so is the best choice here.
return (static_cast<int>(floor(log2(std::abs(n)))));
}

int msb2(const int64_t& n_in)
{
int64_t n = n_in;

int index = 0, count = 0;
while(n != 0) {
count++;
if(n % 2 == 1) {
index = count;
}
n /= 2;
}
return (1 << (index - 1));
}
} //anonymous namespace

BOOST_AUTO_TEST_SUITE(sidestake_tests)

BOOST_AUTO_TEST_CASE(sidestake_Allocation_msb_performance_test)
{
// This is a test to bracket the two different primary algorithms for doing msb calcs. The first is O(1), the second
// is O(log n), but the O(1) straight from the C++ library is pretty heavyweight and highly dependent on CPU architecture.

FastRandomContext rand(uint256 {0});

unsigned int iterations = 10000000;

g_timer.InitTimer("msb_test", true);

for (unsigned int i = 0; i < iterations; ++i) {
msb(rand.rand64());
}

int64_t msb_test_time = g_timer.GetTimes(strprintf("msb %u iterations", iterations), "msb_test").time_since_last_check;

FastRandomContext rand2(uint256 {0});

for (unsigned int i = 0; i < iterations; ++i) {
msb2(rand2.rand64());
}

int64_t msb2_test_time = g_timer.GetTimes(strprintf("msb2 %u iterations", iterations), "msb_test").time_since_last_check;

// The execution time of the above on a 13900K is

// INFO: GetTimes: timer msb_test: msb 10000000 iterations: elapsed time: 86 ms, time since last check: 86 ms.
// INFO: GetTimes: timer msb_test: msb2 10000000 iterations: elapsed time: 168 ms, time since last check: 82 ms.

// Which is almost identical.

// One can easily have T1 = k1 * O(1) and T2 = k2 * O(n) = k2 * n * O(1) where T1 > T2 for n < q if k1 > q * k2.

// This test makes sure that the two algorithms are within 50% of one another on execution time. If not, it will
// fail to prompt us to look at this again.
BOOST_CHECK(((double) std::abs(msb2_test_time - msb_test_time)) / (double) msb_test_time < 0.5);
}

BOOST_AUTO_TEST_CASE(sidestake_Allocation_Initialization_trivial)
{
GRC::Allocation allocation;
Expand Down

0 comments on commit cdf6b15

Please sign in to comment.