DOLFINx 0.10.0.0
DOLFINx C++ interface
Loading...
Searching...
No Matches
Timer.h
1// Copyright (C) 2008-2015 Anders Logg, Jan Blechta, Paul T. Kühner and Garth N.
2// Wells
3//
4// This file is part of DOLFINx (https://www.fenicsproject.org)
5//
6// SPDX-License-Identifier: LGPL-3.0-or-later
7
8#pragma once
9
10#include <chrono>
11#include <optional>
12#include <stdexcept>
13#include <string>
14
15#include "TimeLogger.h"
16
17namespace dolfinx::common
18{
39template <typename T = std::chrono::high_resolution_clock>
40class Timer
41{
42public:
51 Timer(std::optional<std::string> task = std::nullopt) : _task(task) {}
52
56 {
57 if (_start_time.has_value() and _task.has_value())
58 {
59 _acc += T::now() - *_start_time;
61 }
62 }
63
65 void start()
66 {
67 _acc = T::duration::zero();
68 _start_time = T::now();
69 }
70
76 template <typename Period = std::ratio<1>>
77 std::chrono::duration<double, Period> elapsed() const
78 {
79 if (_start_time.has_value()) // Timer is running
80 return T::now() - *_start_time + _acc;
81 else // Timer is stopped
82 return _acc;
83 }
84
90 template <typename Period = std::ratio<1>>
91 std::chrono::duration<double, Period> stop()
92 {
93 if (_start_time.has_value()) // Timer is running
94 {
95 _acc += T::now() - *_start_time;
96 _start_time = std::nullopt;
97 }
98
99 return _acc;
100 }
101
105 void resume()
106 {
107 if (!_start_time.has_value())
108 _start_time = T::now();
109 }
110
118 void flush()
119 {
120 if (_start_time.has_value())
121 throw std::runtime_error("Timer must be stopped before flushing.");
122
123 if (_task.has_value())
124 {
126 _task = std::nullopt;
127 }
128 }
129
130private:
131 // Name of task to register in logger
132 std::optional<std::string> _task;
133
134 // Elapsed time offset
135 T::duration _acc = T::duration::zero();
136
137 // Store start time (std::nullopt if timer has been stopped)
138 std::optional<typename T::time_point> _start_time = T::now();
139};
140} // namespace dolfinx::common
void register_timing(std::string task, std::chrono::duration< double, std::ratio< 1 > > wall)
Register timing (for later summary)
Definition TimeLogger.cpp:23
static TimeLogger & instance()
Singleton access.
Definition TimeLogger.cpp:16
Timer for measuring and logging elapsed time durations.
Definition Timer.h:41
std::chrono::duration< double, Period > stop()
Stop timer and return elapsed time.
Definition Timer.h:91
void resume()
Resume a stopped timer.
Definition Timer.h:105
~Timer()
Definition Timer.h:55
void start()
Reset elapsed time and (re-)start timer.
Definition Timer.h:65
std::chrono::duration< double, Period > elapsed() const
Elapsed time since time has been started.
Definition Timer.h:77
Timer(std::optional< std::string > task=std::nullopt)
Create and start timer.
Definition Timer.h:51
void flush()
Flush timer duration to the logger.
Definition Timer.h:118
Miscellaneous classes, functions and types.
Definition dolfinx_common.h:8