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