Maze Builder Docs 8.10.23
Loading...
Searching...
No Matches
progress.h
Go to the documentation of this file.
1#ifndef PROGRESS_H
2#define PROGRESS_H
3
4#include <chrono>
5#include <functional>
6#include <mutex>
7#include <utility>
8#include <type_traits>
9
12namespace mazes
13{
14
19 template <typename Time = std::chrono::milliseconds, typename Clock = std::chrono::high_resolution_clock>
20 class progress
21 {
22 mutable std::mutex mtx;
23 Clock::time_point start_time;
24 Clock::time_point end_time;
25
26 public:
27 explicit progress() : start_time(Clock::now()), end_time(start_time)
28 {
29 }
30
39 template <typename F, typename... Args, typename Duration = Time>
40 static Duration duration(F &&f, Args &&...args)
41 {
42 progress p;
43 p.start();
44
45 if constexpr (std::is_void_v<std::invoke_result_t<std::decay_t<F>, std::decay_t<Args>...>>)
46 {
47 std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
48 }
49 else
50 {
51 const auto result = std::invoke(std::forward<F>(f), std::forward<Args>(args)...);
52 if (!result)
53 {
54 return Duration::zero();
55 }
56 }
57
58 auto duration = p.elapsed<Duration>();
59 return duration;
60 }
61
63 void start() noexcept
64 {
65 std::lock_guard<std::mutex> lock(this->mtx);
66 start_time = end_time = Clock::now();
67 }
68
70 void reset() noexcept
71 {
72 this->start();
73 }
74
78 template <typename T = double>
79 T elapsed() noexcept
80 {
81 std::lock_guard<std::mutex> lock(this->mtx);
82 end_time = Clock::now();
83 return static_cast<T>(std::chrono::duration_cast<Time>(end_time - start_time).count());
84 }
85
86 static double to_double_from_duration(const std::chrono::duration<double> &duration) noexcept
87 {
88 return duration.count();
89 }
90 }; // progress
91
92} // namespace mazes
93
94#endif // PROGRESS_H
Command-line argument handler with JSON support.
Definition args.h:19
void start() noexcept
Start the progress.
Definition progress.h:63
static Duration duration(F &&f, Args &&...args)
Measures the duration of a callable object.
Definition progress.h:40
T elapsed() noexcept
Capture the elapsed time.
Definition progress.h:79
void reset() noexcept
Reset the progress.
Definition progress.h:70