Clock.h
1 /* This file is part of the Gudhi Library - https://gudhi.inria.fr/ - which is released under MIT.
2  * See file LICENSE or go to https://gudhi.inria.fr/licensing/ for full license details.
3  * Author(s): David Salinas
4  *
5  * Copyright (C) 2014 Inria
6  *
7  * Modification(s):
8  * - YYYY/MM Author: Description of the modification
9  */
10 
11 #ifndef CLOCK_H_
12 #define CLOCK_H_
13 
14 #include <iostream>
15 #include <string>
16 #include <chrono>
17 
18 namespace Gudhi {
19 
20 class Clock {
21  public:
22  // Construct and start the timer
23  Clock(const std::string& msg_ = std::string())
24  : startTime(std::chrono::system_clock::now()),
25  end_called(false),
26  msg(msg_) { }
27 
28  // Restart the timer
29  void begin() const {
30  end_called = false;
31  startTime = std::chrono::system_clock::now();
32  }
33 
34  // Stop the timer
35  void end() const {
36  end_called = true;
37  endTime = std::chrono::system_clock::now();
38  }
39 
40  std::string message() const {
41  return msg;
42  }
43 
44  // Print current value to std::clog
45  void print() const {
46  std::clog << *this << std::endl;
47  }
48 
49  friend std::ostream& operator<<(std::ostream& stream, const Clock& clock) {
50  if (!clock.msg.empty())
51  stream << clock.msg << ": ";
52 
53  stream << clock.num_seconds() << "s\n";
54  return stream;
55  }
56 
57  // Get the number of seconds between the timer start and:
58  // - the last call of end() if it was called
59  // - or now otherwise. In this case, the timer is not stopped.
60  double num_seconds() const {
61  if (!end_called) {
62  auto end = std::chrono::system_clock::now();
63  return std::chrono::duration_cast<std::chrono::milliseconds>(end-startTime).count() / 1000.;
64  } else {
65  return std::chrono::duration_cast<std::chrono::milliseconds>(endTime-startTime).count() / 1000.;
66  }
67  }
68 
69  private:
70  mutable std::chrono::time_point<std::chrono::system_clock> startTime, endTime;
71  mutable bool end_called;
72  std::string msg;
73 };
74 
75 } // namespace Gudhi
76 
77 #endif // CLOCK_H_
GUDHI  Version 3.4.1  - C++ library for Topological Data Analysis (TDA) and Higher Dimensional Geometry Understanding.  - Copyright : MIT Generated on Thu Dec 23 2021 15:37:05 for GUDHI by Doxygen 1.9.1