From 34f3d29d93ec2923d413dd0e47f569cf5122bac6 Mon Sep 17 00:00:00 2001 From: gabime Date: Sat, 29 Aug 2020 02:48:43 +0300 Subject: Added stopwatch support --- include/spdlog/stopwatch.h | 61 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 include/spdlog/stopwatch.h (limited to 'include/spdlog/stopwatch.h') diff --git a/include/spdlog/stopwatch.h b/include/spdlog/stopwatch.h new file mode 100644 index 00000000..770ddea1 --- /dev/null +++ b/include/spdlog/stopwatch.h @@ -0,0 +1,61 @@ +// Copyright(c) 2015-present, Gabi Melman & spdlog contributors. +// Distributed under the MIT License (http://opensource.org/licenses/MIT) + +#pragma once + +#include + +// Stopwatch support for spdlog (using std::chrono::high_resolution_clock). +// Displays elapsed seconds since construction as double. +// +// Usage: +// +// spdlog::stopwatch sw; +// ... +// spdlog::debug("Elapsed: {} seconds", sw); => "Elapsed 0.005116733 seconds" +// spdlog::info("Elapsed: {:.6} seconds", sw); => "Elapsed 0.005163 seconds" +// +// +// If other units are needed (e.g. millis instead of double), include "fmt/chrono.h" and use "duration_cast<..>(sw.elapsed())": +// +// #include +//.. +// using std::chrono::duration_cast; +// using std::chrono::milliseconds; +// spdlog::info("Elapsed {}", duration_cast(sw.elapsed())); => "Elapsed 5ms" + +namespace spdlog { +class stopwatch +{ + using clock = std::chrono::high_resolution_clock; + std::chrono::time_point start_tp_; + +public: + stopwatch() + : start_tp_{clock::now()} + {} + + std::chrono::duration elapsed() const + { + return std::chrono::duration(clock::now() - start_tp_); + } + + void reset() + { + start_tp_ = clock ::now(); + } +}; +} // namespace spdlog + +// Support for fmt formatting (e.g. "{:012.9}" or just "{}") +namespace fmt { +template<> +struct formatter : formatter +{ + template + auto format(const spdlog::stopwatch &sw, FormatContext &ctx) -> decltype(ctx.out()) + { + return formatter::format(sw.elapsed().count(), ctx); + } +}; +} // namespace fmt -- cgit v1.2.3