1010#include " TimeLogManager.h"
1111#include < chrono>
1212#include < optional>
13+ #include < stdexcept>
1314#include < string>
1415
1516namespace dolfinx ::common
@@ -50,17 +51,12 @@ class Timer
5051 // / registered in the logger.
5152 ~Timer ()
5253 {
53- if (_start_time.has_value ()) // Timer is running
54- {
55- _acc += T::now () - _start_time.value ();
56- _start_time = std::nullopt ;
57- }
58-
59- if (_task.has_value ())
54+ if (_start_time.has_value () and _task.has_value ())
6055 {
56+ _acc += T::now () - *_start_time;
6157 using X = std::chrono::duration<double , std::ratio<1 >>;
6258 TimeLogManager::logger ().register_timing (
63- _task. value () , std::chrono::duration_cast<X>(_acc).count ());
59+ * _task, std::chrono::duration_cast<X>(_acc).count ());
6460 }
6561 }
6662
@@ -80,8 +76,8 @@ class Timer
8076 std::chrono::duration<double , Period> elapsed () const
8177 {
8278 if (_start_time.has_value ()) // Timer is running
83- return T::now () - _start_time. value () + _acc;
84- else // Timer is stoped
79+ return T::now () - * _start_time + _acc;
80+ else // Timer is stopped
8581 return _acc;
8682 }
8783
@@ -95,21 +91,49 @@ class Timer
9591 {
9692 if (_start_time.has_value ()) // Timer is running
9793 {
98- _acc += T::now () - _start_time. value () ;
94+ _acc += T::now () - * _start_time;
9995 _start_time = std::nullopt ;
10096 }
10197
10298 return _acc;
10399 }
104100
101+ // / @brief Resume a stopped timer.
102+ // /
103+ // / Does nothing if timer has not been stopped.
104+ void resume ()
105+ {
106+ if (!_start_time.has_value ())
107+ _start_time = T::now ();
108+ }
109+
110+ // / @brief Flush timer duration to the logger.
111+ // /
112+ // / Timer can be flushed only once.
113+ // /
114+ // / @pre Timer must have been stopped before flushing.
115+ void flush ()
116+ {
117+ if (_start_time.has_value ())
118+ throw std::runtime_error (" Timer must be stopped before flushing." );
119+
120+ if (_task.has_value ())
121+ {
122+ using X = std::chrono::duration<double , std::ratio<1 >>;
123+ TimeLogManager::logger ().register_timing (
124+ *_task, std::chrono::duration_cast<X>(_acc).count ());
125+ _task = std::nullopt ;
126+ }
127+ }
128+
105129private:
106130 // Name of task to register in logger
107131 std::optional<std::string> _task;
108132
109133 // Elapsed time offset
110134 T::duration _acc = T::duration::zero();
111135
112- // Store start time * std::nullopt if timer has been stopped)
136+ // Store start time ( std::nullopt if timer has been stopped)
113137 std::optional<typename T::time_point> _start_time = T::now();
114138};
115139} // namespace dolfinx::common
0 commit comments