intersection_bench/test.cpp
2025-04-28 14:20:30 +03:00

112 lines
2.7 KiB
C++

#include <catch2/catch_test_macros.hpp>
#include <catch2/benchmark/catch_benchmark_all.hpp>
#include <cmath>
#include <random>
#define CATCH_CONFIG_MAIN
#include <catch2/catch_all.hpp>
struct Circle
{
double X;
double Y;
double R;
};
bool circle_circle_intersect(const Circle& a, const Circle& b)
{
auto dx = a.X - b.X;
auto dy = a.Y - b.Y;
auto distance = std::sqrt(dx*dx + dy*dy);
return distance < a.R + b.R;
}
bool circle_circle_intersect2(const Circle& a, const Circle& b)
{
auto dx = a.X - b.X;
auto dy = a.Y - b.Y;
auto r_sum = a.R + b.R;
return dx*dx + dy*dy < r_sum * r_sum;
}
std::random_device dev;
std::mt19937 rng(dev());
Circle generate_random_circle()
{
static std::uniform_real_distribution pos_dist(0.0f, 100.0f);
static std::uniform_real_distribution r_dist(5.0f, 15.0f);
return Circle
{
.X = pos_dist(rng),
.Y = pos_dist(rng),
.R = r_dist(rng)
};
}
TEST_CASE("Oh Hi Mark", "[test]")
{
BENCHMARK_ADVANCED("Circle circle (sqrt) [1000]")(
Catch::Benchmark::Chronometer meter)
{
std::vector<Circle> circles;
circles.reserve(1000);
for(int i = 0; i < 1000; ++i)
{
circles.emplace_back(generate_random_circle());
}
meter.measure(
[&]
{
int total = 0;
for(size_t i = 0; i < circles.size(); ++i)
{
const auto& a = circles[i];
for(size_t j = i + 1; j < circles.size(); ++j)
{
const auto& b = circles[j];
auto collision = circle_circle_intersect(a, b);
total += collision;
}
}
return total;
});
};
BENCHMARK_ADVANCED("Circle circle (no sqrt) [1000]")(
Catch::Benchmark::Chronometer meter)
{
std::vector<Circle> circles;
circles.reserve(1000);
for(int i = 0; i < 1000; ++i)
{
circles.emplace_back(generate_random_circle());
}
meter.measure(
[&]
{
int total = 0;
for(size_t i = 0; i < circles.size(); ++i)
{
const auto& a = circles[i];
for(size_t j = i + 1; j < circles.size(); ++j)
{
const auto& b = circles[j];
auto collision = circle_circle_intersect2(a, b);
total += collision;
}
}
return total;
});
};
}