sandbox
Loading...
Searching...
No Matches
timer.hpp
1// SPDX-License-Identifier: MIT
2#ifndef LIBSBX_UTILITY_TIMER_HPP_
3#define LIBSBX_UTILITY_TIMER_HPP_
4
5#include <chrono>
6#include <cmath>
7#include <functional>
8#include <type_traits>
9
10#include <libsbx/units/time.hpp>
11
12namespace sbx::utility {
13
14class timer {
15
16public:
17
18 timer();
19
20 ~timer() = default;
21
22 auto elapsed() noexcept -> units::second;
23
24private:
25
26 std::chrono::time_point<std::chrono::high_resolution_clock> _start{};
27
28}; // class timer
29
31
32public:
33
34 template<typename Callable>
35 requires (std::is_invocable_v<Callable, const units::second&>)
36 scoped_timer(Callable&& callable)
37 : _on_destroy{std::forward<Callable>(callable)},
38 _start{std::chrono::high_resolution_clock::now()} { }
39
41 if (_on_destroy) {
42 const auto now = std::chrono::high_resolution_clock::now();
43 const auto elapsed = units::second{std::chrono::duration_cast<std::chrono::duration<std::float_t>>(now - _start).count()};
44
45 std::invoke(_on_destroy, elapsed);
46 }
47 }
48
49private:
50
51 std::function<void(const units::second&)> _on_destroy;
52 std::chrono::time_point<std::chrono::high_resolution_clock> _start;
53
54}; // class scoped_timer
55
56} // namespace sbx::utility
57
58#endif // LIBSBX_UTILITY_TIMER_HPP_
Definition: quantity.hpp:66
Definition: timer.hpp:30
Definition: timer.hpp:14