$darkmode
timer.hpp
Go to the documentation of this file.
1 /*
2  * Copyright 2020 Robert Bosch GmbH
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  * SPDX-License-Identifier: Apache-2.0
17  */
36 #pragma once
37 
38 #include <chrono> // for now, duration, ...
39 #include <functional> // for functional<>
40 
41 namespace timer {
42 
43 using Milliseconds = std::chrono::duration<double, std::milli>;
44 using TimePoint = std::chrono::high_resolution_clock::time_point;
45 
46 class ScopeTimer {
47  public:
48  explicit ScopeTimer(std::function<void(TimePoint, TimePoint)> fn) : fn_(fn) {
49  start_ = std::chrono::high_resolution_clock::now();
50  }
51 
52  ScopeTimer(const ScopeTimer&) = delete;
53  ScopeTimer& operator=(const ScopeTimer&) = delete;
54  ScopeTimer(ScopeTimer&&) = delete;
55  ScopeTimer const& operator=(ScopeTimer&&) = delete;
56 
57  ~ScopeTimer() {
58  auto end = std::chrono::high_resolution_clock::now();
59  fn_(start_, end);
60  }
61 
62  private:
63  TimePoint start_;
64  std::function<void(TimePoint, TimePoint)> fn_;
65 };
66 
67 template <typename P = Milliseconds>
69  public:
70  DurationTimer() { this->reset(); }
71  explicit DurationTimer(std::function<void(P)> fn) : fn_(fn) { this->reset(); }
72 
73  DurationTimer(const DurationTimer&) = delete;
74  DurationTimer& operator=(const DurationTimer&) = delete;
75  DurationTimer(DurationTimer&&) = delete;
76  DurationTimer const& operator=(DurationTimer&&) = delete;
77 
78  ~DurationTimer() {
79  auto end = std::chrono::high_resolution_clock::now();
80  if (fn_) {
81  fn_(std::chrono::duration_cast<P>(end - start_));
82  }
83  }
84 
85  P reset() {
86  auto previous_start = start_;
87  start_ = std::chrono::high_resolution_clock::now();
88  return std::chrono::duration_cast<P>(start_ - previous_start);
89  }
90 
91  P elapsed() {
92  auto now = std::chrono::high_resolution_clock::now();
93  return std::chrono::duration_cast<P>(now - start_);
94  }
95 
96  private:
97  TimePoint start_;
98  std::function<void(P)> fn_;
99 };
100 
101 } // namespace timer
Definition: timer.hpp:68
Definition: timer.hpp:46