Stopwatch.cpp
Go to the documentation of this file.
1 #include "Stopwatch.h"
2 
3 namespace stopwatch
4 {
6  {
7  }
8 
9  void
11  {
12  statsMap.clear();
13  currentStarts.clear();
14  }
15 
16  void
17  Stopwatch::start(const std::string& tag)
18  {
19  // implicit construction by [] operator
20  currentStarts[tag] = Clock::now();
21  }
22 
23  void
24  Stopwatch::stop(const std::string& tag)
25  {
26  TimePoint end = Clock::now();
27 
28  auto it = currentStarts.find(tag);
29  if (it == currentStarts.end())
30  {
31  return; // not started, ignore
32  }
33 
34  TimePoint start = it->second;
35  Duration elapsed = end - start;
36 
37  Stats& stats = statsMap[tag];
38 
39  stats.totalExecutionTime += elapsed;
40  stats.numExecutions++;
41 
42  stats.latestExecutionTime = elapsed;
44  }
45 
46  const Stats&
47  Stopwatch::getStats(const std::string& tag)
48  {
49  return statsMap[tag];
50  }
51 
52  std::ostream&
53  operator<<(std::ostream& os, const Stats& stats)
54  {
55  os << "Total execution time: " << stats.totalExecutionTime.count() << " seconds"
56  << std::endl;
57  os << "Total number of executions: " << stats.numExecutions << std::endl;
58  os << "Average execution time: " << stats.averageExecutionTime.count() << " seconds"
59  << std::endl;
60  return os;
61  }
62 
63  std::ostream&
64  operator<<(std::ostream& os, const Stopwatch& stats)
65  {
66  for (auto it : stats.statsMap)
67  {
68  os << "== Stats for '" << it.first << "' ==" << std::endl;
69  os << it.second;
70  }
71  return os;
72  }
73 
74 } // namespace stopwatch
stopwatch::TimePoint
std::chrono::time_point< Clock > TimePoint
Definition: Stopwatch.h:12
Stopwatch.h
stopwatch::Stats::latestExecutionTime
Duration latestExecutionTime
Definition: Stopwatch.h:25
stopwatch::Stats::numExecutions
std::size_t numExecutions
Definition: Stopwatch.h:21
stopwatch::Stats::totalExecutionTime
Duration totalExecutionTime
Definition: Stopwatch.h:22
stopwatch::Stopwatch::Stopwatch
Stopwatch()
Definition: Stopwatch.cpp:5
stopwatch::Stopwatch::reset
void reset()
Definition: Stopwatch.cpp:10
stopwatch::Stats
Definition: Stopwatch.h:14
stopwatch
Definition: Stopwatch.cpp:3
stopwatch::Stopwatch::getStats
const Stats & getStats(const std::string &tag)
Definition: Stopwatch.cpp:47
stopwatch::Stopwatch::stop
void stop(const std::string &tag)
Definition: Stopwatch.cpp:24
stopwatch::Stopwatch
Definition: Stopwatch.h:30
stopwatch::Duration
std::chrono::duration< float > Duration
Definition: Stopwatch.h:11
stopwatch::operator<<
std::ostream & operator<<(std::ostream &os, const Stats &stats)
Definition: Stopwatch.cpp:53
stopwatch::Stats::averageExecutionTime
Duration averageExecutionTime
Definition: Stopwatch.h:24
stopwatch::Stopwatch::start
void start(const std::string &tag)
Definition: Stopwatch.cpp:17