From 2644dc8128276c91ae20a71c2010cc15460e9ffb Mon Sep 17 00:00:00 2001 From: Lucas Alber Date: Mon, 4 Nov 2024 13:03:14 +0100 Subject: [PATCH] merian: utils: Add formatter for stopwatch --- include/merian/utils/stopwatch.hpp | 4 ++++ include/merian/utils/string.hpp | 21 ++++++++++++++++----- src/merian/utils/stopwatch.cpp | 9 +++++++++ 3 files changed, 29 insertions(+), 5 deletions(-) diff --git a/include/merian/utils/stopwatch.hpp b/include/merian/utils/stopwatch.hpp index 67ac9b2d..dce0b647 100644 --- a/include/merian/utils/stopwatch.hpp +++ b/include/merian/utils/stopwatch.hpp @@ -17,8 +17,12 @@ class Stopwatch { double seconds() const; std::chrono::nanoseconds duration() const; + friend std::ostream& operator<<(std::ostream& stream, const Stopwatch& sw); + private: chrono_clock::time_point start; }; +auto format_as(const Stopwatch& sw); + } // namespace merian diff --git a/include/merian/utils/string.hpp b/include/merian/utils/string.hpp index a4b0dec5..68e37908 100644 --- a/include/merian/utils/string.hpp +++ b/include/merian/utils/string.hpp @@ -9,15 +9,26 @@ namespace merian { -[[nodiscard]] inline std::string format_size(const uint64_t size) { - std::vector units = {"B", "KB", "MB", "GB", "TB"}; +[[nodiscard]] inline std::string format_size(const uint64_t size_bytes) { + const std::vector units = {"B", "KB", "MB", "GB", "TB"}; std::size_t unit_index; - if (size == 0) { + if (size_bytes == 0) { unit_index = 0; } else { - unit_index = std::min((std::size_t)std::log2(size) / 10, units.size() - 1); + unit_index = std::min((std::size_t)std::log2(size_bytes) / 10, units.size() - 1); } - return fmt::format("{} {}", size / std::pow(1024, unit_index), units[unit_index]); + return fmt::format("{} {}", (double)size_bytes / std::pow(1024, unit_index), units[unit_index]); +} + +[[nodiscard]] inline std::string format_duration(const uint64_t duration_ns) { + const std::vector units = {"ns", "μs", "ms", "s"}; + std::size_t unit_index; + if (duration_ns == 0) { + unit_index = 0; + } else { + unit_index = std::min((std::size_t)(std::log10(duration_ns) / 3), units.size() - 1); + } + return fmt::format("{} {}", (double)duration_ns / std::pow(1000, unit_index), units[unit_index]); } [[nodiscard]] inline bool ends_with(const std::string& value, const std::string& suffix) { diff --git a/src/merian/utils/stopwatch.cpp b/src/merian/utils/stopwatch.cpp index 9c7b330c..ce826572 100644 --- a/src/merian/utils/stopwatch.cpp +++ b/src/merian/utils/stopwatch.cpp @@ -1,5 +1,6 @@ #include "merian/utils/stopwatch.hpp" #include "merian/utils/chrono.hpp" +#include "merian/utils/string.hpp" #include namespace merian { @@ -37,4 +38,12 @@ std::chrono::nanoseconds Stopwatch::duration() const { return end - start; } +std::ostream& operator<<(std::ostream& stream, const Stopwatch& sw) { + return stream << format_duration(sw.nanos()); +} + +auto format_as(const Stopwatch& sw) { + return format_duration(sw.nanos()); +} + } // namespace merian