Documentation of CSL
timer.h
Go to the documentation of this file.
1 // This file is part of MARTY.
2 //
3 // MARTY is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // MARTY is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with MARTY. If not, see <https://www.gnu.org/licenses/>.
15 
23 #ifndef TIMER_H_INCLUDED
24 #define TIMER_H_INCLUDED
25 
26 #include <iostream>
27 #include <ctime>
28 #include <cmath>
29 #include <sstream>
30 
31 namespace csl {
32 
33 class Timer {
34 
35  private:
36 
37  std::clock_t start;
38 
39  public:
40 
41  std::ostream &out = std::cout;
42 
43  Timer() {
44  start = std::clock();
45  }
46 
47  Timer(Timer const &other)
48  :start(other.start),
49  out(other.out)
50  {}
51  Timer &operator=(Timer const &other)
52  {
53  start = other.start;
54  return *this;
55  }
56 
57  ~Timer() {
58  display();
59  }
60 
61  void restart() {
62  display();
63  start = std::clock();
64  }
65 
66  void display() {
67  out << "Elapsed time : " << elapsedTime(std::clock() - start)
68  << std::endl;
69  }
70 
71  private:
72 
73  static
74  int getSecondsFromTime(std::clock_t time)
75  {
76  return time * 1./CLOCKS_PER_SEC;
77  }
78 
79  static
80  int getModulo(int& init, int modulo)
81  {
82  int res = init / modulo;
83  init -= modulo * res;
84  return res;
85  }
86 
87  static
88  std::string getStringFromTime(int number, int nDigits = 2)
89  {
90  std::ostringstream sout;
91  if (number < std::pow(10, nDigits-1))
92  for (int i = 0; i != nDigits-1; ++i)
93  sout << 0;
94  sout << number;
95  return sout.str();
96  }
97 
98  static
99  std::string elapsedTime(std::clock_t time)
100  {
101  int nSec = getSecondsFromTime(time);
102  int nMili = 1000*(time*1./CLOCKS_PER_SEC-nSec);
103  int nHours = getModulo(nSec, 3600);
104  int nMin = getModulo(nSec, 60);
105 
106  return getStringFromTime(nHours) + "h "
107  + getStringFromTime(nMin) + "m "
108  + getStringFromTime(nSec) + "s "
109  + getStringFromTime(nMili, 2) + "ms";
110  }
111 
112 };
113 
114 }
115 
116 #endif
Namespace for csl library.
Definition: abreviation.h:34
Definition: timer.h:33