Utilities
Utilities header only library
Time.h
1 /*
2  Copyright (C) Skeletex Research, s.r.o. - All Rights Reserved
3  Unauthorized copying of this file, via any medium is strictly prohibited
4  Proprietary and confidential
5 */
6 #ifndef UTILS_TIME_H
7 #define UTILS_TIME_H
8 #include <string>
9 #include <ctime>
10 #include <chrono>
11 #include <list>
12 #include <assert.h>
13 
14 #define __STDC_WANT_LIB_EXT1__ 1
15 #include <time.h>
16 #include <stdio.h>
17 
18 #include <Utils/ExtSTD.h>
19 
21 namespace time_m
22 {
23 
24  using DateTime = std::chrono::system_clock::time_point;
25 
27  inline DateTime Now()
28  {
29  return std::chrono::system_clock::now();
30  }
31 
32 
34  inline double NowMs()
35  {
36  return (double)std::chrono::duration_cast<std::chrono::milliseconds>
37  (Now().time_since_epoch()).count();
38  }
39 
40 
42  inline double NowS()
43  {
44  return (double)std::chrono::duration_cast<std::chrono::milliseconds>
45  (Now().time_since_epoch()).count() * 0.001f;
46  }
47 
48 
54  inline std::string ToString(const DateTime &date_time, const std::string &format = "%Y_%m_%d_%H_%M_%S")
55  {
56  time_t rawtime = std::chrono::system_clock::to_time_t(date_time);
57  char buffer[80];
58 
59  // https://stackoverflow.com/a/38034148/2621721
60  std::tm timeinfo{};
61 #if defined(__unix__)
62  localtime_r(&rawtime, &timeinfo);
63 #elif defined(_MSC_VER)
64  localtime_s(&timeinfo, &rawtime);
65 #else
66  static std::mutex mtx;
67  std::lock_guard<std::mutex> lock(mtx);
68  timeinfo = *std::localtime(&rawtime);
69 #endif
70 
71  strftime(buffer, 80, format.c_str(), &timeinfo);
72  return std::string(buffer);
73  }
74 
75 
80  inline std::string NowStr(const std::string &format = "%Y_%m_%d_%H_%M_%S")
81  {
82  return ToString(std::chrono::system_clock::now(), format);
83  }
84 
85 
87  inline int64_t MicrosecondsBetween(const DateTime &datetime1, const DateTime &datetime2)
88  {
89  return abs(std::chrono::duration_cast<std::chrono::microseconds>(datetime1 - datetime2).count());
90  }
91 
92 
94  inline double SecondsBetween(const DateTime &datetime1, const DateTime &datetime2)
95  {
96  return 0.000001 * (double)MicrosecondsBetween(datetime1, datetime2);
97  }
98 
99  class FPSCounter
100  {
101  public:
102  FPSCounter()
103  {
104  lastFrameTime = Now();
105  };
106  void RegisterFrame()
107  {
108  const DateTime now = Now();
109  fps = 1.0 / SecondsBetween(lastFrameTime, now);
110  lastFrameTime = now;
111  };
112  double Get() { return fps; };
113  const double *GetPtr() { return &fps; };
114  private:
115  DateTime lastFrameTime;
116  double fps = 0.0;
117  };
118 
119 
120 
122  class StopWatch
123  {
124  public:
126  StopWatch() = default;
128  void Reset() { start_time_ = NowMs(); };
130  double GetTime() { return NowMs() - start_time_; };
132  std::string GetTimeStr() { return std::to_string(GetTime()); };
133  private:
134  double start_time_{ NowMs() };
135  };
136 
137 
138 
141  {
142  private:
143  struct Measurement
144  {
145  Measurement(const std::string &n, const double t) : name(n), start_time(t) {};
146  std::string name;
147  double start_time;
148  double duration = -1.0f;
149  Measurement *parent = nullptr;
150  std::list<Measurement> children;
151  };
152  public:
153  TimeLogger() = default;
154 
155  virtual void MeasureStart(const std::string &measurement_name)
156  {
157  auto start_time = (double)std::chrono::duration_cast<std::chrono::milliseconds>
158  (Now().time_since_epoch()).count();
159  if (root_measure_ == nullptr)
160  {
161  root_measure_ = std::make_unique<Measurement>(measurement_name, start_time);
162  active_measure_ = root_measure_.get();
163  }
164  else
165  {
166  active_measure_->children.emplace_back(measurement_name, start_time);
167  active_measure_->children.back().parent = active_measure_;
168  active_measure_ = &active_measure_->children.back();
169  }
170  };
171 
172  virtual void MeasureEnd(std::ostream *output_log)
173  {
174  if (active_measure_ == nullptr)
175  {
176  *output_log << "Time Measurement Error: MeasureEnd() - no matching MeasureStart() was called\n";
177  return;
178  }
179 
180  auto end_time = (double)std::chrono::duration_cast<std::chrono::milliseconds>
181  (Now().time_since_epoch()).count();
182 
183  active_measure_->duration = end_time - active_measure_->start_time;
184 
185  if (active_measure_->parent)
186  {
187  active_measure_ = active_measure_->parent;
188  return;
189  }
190  WriteMeasurementRecursive(active_measure_, output_log);
191  root_measure_.reset();
192  active_measure_ = nullptr;
193  }
194 
195  TimeLogger(const TimeLogger &) = delete;
196  TimeLogger &operator=(const TimeLogger &) = delete;
197 
198  ~TimeLogger()
199  {
200  assert(active_measure_ == nullptr); // not enough calls of MeasureEnd()
201  };
202 
203  private:
204  std::unique_ptr<Measurement> root_measure_;
205  Measurement *active_measure_ = nullptr;
206 
207  void WriteMeasurement(const Measurement *msr, std::ostream *output_log, uint8_t level = 0)
208  {
209  *output_log << std::string(level, '\t')
210  << msr->duration << " ms"
211  << " - "
212  << msr->name
213  << std::endl;
214  }
215 
216  void WriteMeasurementRecursive(const Measurement *msr, std::ostream *output_log, const uint8_t level = 0)
217  {
218  WriteMeasurement(msr, output_log, level);
219  for (const auto &child : msr->children)
220  {
221  WriteMeasurementRecursive(&child, output_log, level + 1);
222  }
223  }
224  };
225 
226 
227 
229  class FileTimeLogger : public TimeLogger
230  {
231  public:
232  void SessionStart(const std::string &export_file_name = "timing_log.local.txt")
233  {
234  export_file_.open(export_file_name);
235  is_session_ = true;
236  }
237 
238  void SessionEnd()
239  {
240  export_file_.close();
241  is_session_ = false;
242  }
243 
244  bool IsSession() const
245  {
246  return is_session_;
247  };
248 
249  virtual void MeasureStart(const std::string &measurement_name) override
250  {
251  if (IsSession())
252  {
253  TimeLogger::MeasureStart(measurement_name);
254  }
255  }
256 
257  void MeasureEnd()
258  {
259  if (IsSession())
260  {
261  TimeLogger::MeasureEnd(&export_file_);
262  }
263  }
264 
265  private:
266  std::ofstream export_file_;
267  bool is_session_ = false;
268 
269  using TimeLogger::MeasureEnd;
270  };
271 
272 
273 
275  template<typename T>
277  {
278  T result;
279  std::chrono::milliseconds time;
280 
281  ProfilingResult(const T &r, std::chrono::milliseconds t)
282  : result(r)
283  , time(t)
284  {}
285  };
286 
288  template<typename T>
289  inline ProfilingResult<T> ProfileFunctionRun(std::function<T()> Function)
290  {
291  StopWatch stop_watch;
292  const auto result = Function();
293  const auto time = std::chrono::milliseconds(static_cast<uint32_t>(std::round(stop_watch.GetTime())));
294  return time_m::ProfilingResult(result, time);
295  }
296 }
297 
298 #endif /* !UTILS_TIME_H */
The result of profiling function execution. Contains the actual result and the run time...
Definition: Time.h:276
DateTime Now()
Returns current time point.
Definition: Time.h:27
double SecondsBetween(const DateTime &datetime1, const DateTime &datetime2)
Returns duration between two time points in seconds.
Definition: Time.h:94
double GetTime()
Returns current watch time. [ms].
Definition: Time.h:130
std::string NowStr(const std::string &format="%Y_%m_%d_%H_%M_%S")
Returns current time in string form.
Definition: Time.h:80
ProfilingResult< T > ProfileFunctionRun(std::function< T()> Function)
Execute and profile a function.
Definition: Time.h:289
int64_t MicrosecondsBetween(const DateTime &datetime1, const DateTime &datetime2)
Returns duration between two time points in microseconds.
Definition: Time.h:87
Class for measuring time in milliseconds [ms].
Definition: Time.h:122
double NowMs()
Returns current time, as number of milliseconds since epoch start.
Definition: Time.h:34
Measures duration of program parts and logs times into a file.
Definition: Time.h:229
std::string ToString(const DateTime &date_time, const std::string &format="%Y_%m_%d_%H_%M_%S")
Returns specified time in string form.
Definition: Time.h:54
std::string GetTimeStr()
Returns current watch time as a text. [ms].
Definition: Time.h:132
double NowS()
Returns current time, as number of seconds since epoch start.
Definition: Time.h:42
Measures duration of program parts and logs times into a stream.
Definition: Time.h:140
Set of functions and structures for measuring time.
Definition: Time.h:21
void Reset()
Resets time on stopwatch.
Definition: Time.h:128