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