Stopwatch.cpp
Go to the documentation of this file.
1#include "Stopwatch.h"
2
3namespace stopwatch
4{
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;
43 stats.averageExecutionTime = stats.totalExecutionTime / stats.numExecutions;
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
Duration totalExecutionTime
Definition Stopwatch.h:22
const Stats & getStats(const std::string &tag)
Definition Stopwatch.cpp:47
void stop(const std::string &tag)
Definition Stopwatch.cpp:24
void start(const std::string &tag)
Definition Stopwatch.cpp:17
std::ostream & operator<<(std::ostream &os, const Stats &stats)
Definition Stopwatch.cpp:53
std::chrono::duration< float > Duration
Definition Stopwatch.h:11
std::chrono::time_point< Clock > TimePoint
Definition Stopwatch.h:12