Skip to content

Commit

Permalink
merian: utils: Add formatter for stopwatch
Browse files Browse the repository at this point in the history
  • Loading branch information
LDAP committed Nov 4, 2024
1 parent 2ff5b8f commit 2644dc8
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 5 deletions.
4 changes: 4 additions & 0 deletions include/merian/utils/stopwatch.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
21 changes: 16 additions & 5 deletions include/merian/utils/string.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,26 @@

namespace merian {

[[nodiscard]] inline std::string format_size(const uint64_t size) {
std::vector<const char*> units = {"B", "KB", "MB", "GB", "TB"};
[[nodiscard]] inline std::string format_size(const uint64_t size_bytes) {
const std::vector<const char*> 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<const char*> 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) {
Expand Down
9 changes: 9 additions & 0 deletions src/merian/utils/stopwatch.cpp
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#include "merian/utils/stopwatch.hpp"
#include "merian/utils/chrono.hpp"
#include "merian/utils/string.hpp"
#include <atomic>

namespace merian {
Expand Down Expand Up @@ -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

0 comments on commit 2644dc8

Please sign in to comment.