based

Opinionated utility library
git clone git://git.dimitrijedobrota.com/based.git
Log | Files | Refs | README | LICENSE | HACKING | CONTRIBUTING | CODE_OF_CONDUCT | BUILDING

commit a6da8343a8e66450b18f7f88d7890f829c29a17a
parent f8f8eae22a0c8e4ea765fa752715b84373a73bc7
author Dimitrije Dobrota < mail@dimitrijedobrota.com >
date Tue, 18 Mar 2025 17:43:10 +0100

Simple scope timer

Diffstat:
M example/empty_example.cpp | +++++++++++++++++++ -----
M include/based/instrumentation.hpp | +++++++++++++++++++++++++++++++++++++++++++++++

2 files changed, 66 insertions(+), 5 deletions(-)


diff --git a/ example/empty_example.cpp b/ example/empty_example.cpp

@@ -4,11 +4,25 @@


int main()
{
based::count_operations(
16UL,
16UL * 1024 * 1024,
[](const auto& a, const auto& b) { std::sort(a, b); },
based::normalize_nlogn);
{
const based::timer time;

based::count_operations(
16UL,
16UL * 1024 * 1024,
[](const auto& a, const auto& b) { std::sort(a, b); },
based::normalize_nlogn);
}

{
const based::timer time;

based::count_operations(
16UL,
16UL * 1024 * 1024,
[](const auto& a, const auto& b) { std::stable_sort(a, b); },
based::normalize_nlogn);
}

return 0;
}

diff --git a/ include/based/instrumentation.hpp b/ include/based/instrumentation.hpp

@@ -2,6 +2,7 @@


#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <concepts>
#include <cstddef>

@@ -209,4 +210,50 @@ void count_operations(size_t i,

}
}

class timer
{
public:
using clock_t = std::chrono::high_resolution_clock;
using duration_t = std::chrono::microseconds;

timer()
: m_startp(clock_t::now())
{
}

timer(const timer&) = delete;
timer(timer&&) = delete;
timer& operator=(const timer&) = delete;
timer& operator=(timer&&) = delete;

~timer()
{
stop();
std::cout << std::flush;
}

void stop()
{
static const auto count = [](const auto& time)
{
return std::chrono::time_point_cast<duration_t>(time)
.time_since_epoch()
.count();
};

const auto endp = clock_t::now();

const auto start = count(m_startp);
const auto end = count(endp);

const auto duration = end - start;
const auto ms = static_cast<double>(duration) * 0.001;

std::cout << std::format("{}us ({}ms)\n", duration, ms);
}

private:
std::chrono::time_point<clock_t> m_startp;
};

} // namespace based