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 "TimeLogger.h"
11#include <chrono>
12#include <optional>
13#include <stdexcept>
14#include <string>
15
16namespace dolfinx::common
17{
38template <typename T = std::chrono::high_resolution_clock>
39class Timer
40{
41public:
50 Timer(std::optional<std::string> task = std::nullopt) : _task(std::move(task))
51 {
52 }
53
57 {
58 if (_start_time.has_value() and _task.has_value())
59 {
60 _acc += T::now() - *_start_time;
62 }
63 }
64
66 void start()
67 {
68 _acc = T::duration::zero();
69 _start_time = T::now();
70 }
71
77 template <typename Period = std::ratio<1>>
78 std::chrono::duration<double, Period> elapsed() const
79 {
80 if (_start_time.has_value()) // Timer is running
81 return T::now() - *_start_time + _acc;
82 else // Timer is stopped
83 return _acc;
84 }
85
91 template <typename Period = std::ratio<1>>
92 std::chrono::duration<double, Period> stop()
93 {
94 if (_start_time.has_value()) // Timer is running
95 {
96 _acc += T::now() - *_start_time;
97 _start_time = std::nullopt;
98 }
99
100 return _acc;
101 }
102
106 void resume()
107 {
108 if (!_start_time.has_value())
109 _start_time = T::now();
110 }
111
119 void flush()
120 {
121 if (_start_time.has_value())
122 throw std::runtime_error("Timer must be stopped before flushing.");
123
124 if (_task.has_value())
125 {
127 _task = std::nullopt;
128 }
129 }
130
131private:
132 // Name of task to register in logger
133 std::optional<std::string> _task;
134
135 // Elapsed time offset
136 T::duration _acc = T::duration::zero();
137
138 // Store start time (std::nullopt if timer has been stopped)
139 std::optional<typename T::time_point> _start_time = T::now();
140};
141} // namespace dolfinx::common
void register_timing(const 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
std::chrono::duration< double, Period > stop()
Stop timer and return elapsed time.
Definition Timer.h:92
void resume()
Resume a stopped timer.
Definition Timer.h:106
~Timer()
Definition Timer.h:56
void start()
Reset elapsed time and (re-)start timer.
Definition Timer.h:66
std::chrono::duration< double, Period > elapsed() const
Elapsed time since time has been started.
Definition Timer.h:78
Timer(std::optional< std::string > task=std::nullopt)
Create and start timer.
Definition Timer.h:50
void flush()
Flush timer duration to the logger.
Definition Timer.h:119
Miscellaneous classes, functions and types.
Definition dolfinx_common.h:8