$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 #ifndef CLOE_UTILITY_TIMER_HPP_
38 #define CLOE_UTILITY_TIMER_HPP_
39 
40 #include <chrono> // for now, duration, ...
41 #include <functional> // for functional<>
42 
43 namespace timer {
44 
45 using Milliseconds = std::chrono::duration<double, std::milli>;
46 using TimePoint = std::chrono::high_resolution_clock::time_point;
47 
48 class ScopeTimer {
49  public:
50  explicit ScopeTimer(std::function<void(TimePoint, TimePoint)> fn) : fn_(fn) {
51  start_ = std::chrono::high_resolution_clock::now();
52  }
53 
54  ScopeTimer(const ScopeTimer&) = delete;
55  ScopeTimer& operator=(const ScopeTimer&) = delete;
56  ScopeTimer(ScopeTimer&&) = delete;
57  ScopeTimer const& operator=(ScopeTimer&&) = delete;
58 
59  ~ScopeTimer() {
60  auto end = std::chrono::high_resolution_clock::now();
61  fn_(start_, end);
62  }
63 
64  private:
65  TimePoint start_;
66  std::function<void(TimePoint, TimePoint)> fn_;
67 };
68 
69 template <typename P = Milliseconds>
71  public:
72  DurationTimer() { this->reset(); }
73  explicit DurationTimer(std::function<void(P)> fn) : fn_(fn) { this->reset(); }
74 
75  DurationTimer(const DurationTimer&) = delete;
76  DurationTimer& operator=(const DurationTimer&) = delete;
77  DurationTimer(DurationTimer&&) = delete;
78  DurationTimer const& operator=(DurationTimer&&) = delete;
79 
80  ~DurationTimer() {
81  auto end = std::chrono::high_resolution_clock::now();
82  if (fn_) {
83  fn_(std::chrono::duration_cast<P>(end - start_));
84  }
85  }
86 
87  P reset() {
88  auto previous_start = start_;
89  start_ = std::chrono::high_resolution_clock::now();
90  return std::chrono::duration_cast<P>(start_ - previous_start);
91  }
92 
93  P elapsed() {
94  auto now = std::chrono::high_resolution_clock::now();
95  return std::chrono::duration_cast<P>(now - start_);
96  }
97 
98  private:
99  TimePoint start_;
100  std::function<void(P)> fn_;
101 };
102 
103 } // namespace timer
104 
105 #endif // CLOE_UTILITY_TIMER_HPP_
Definition: timer.hpp:43
Definition: timer.hpp:70
Definition: timer.hpp:48