-
Notifications
You must be signed in to change notification settings - Fork 0
/
stopwatch.h
51 lines (46 loc) · 1.75 KB
/
stopwatch.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include <chrono>
#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
/// based on an answer in
/// https://stackoverflow.com/questions/38977879/how-can-i-measure-the-execution-time-of-one-thread
class Stopwatch
{
public:
std::chrono::time_point<std::chrono::high_resolution_clock> start;
std::chrono::time_point<std::chrono::high_resolution_clock> last;
std::string fromWhere = "";
Stopwatch(std::string fromWhere = "")
: start(std::chrono::high_resolution_clock::now())
, last(std::chrono::high_resolution_clock::now())
, fromWhere(fromWhere)
{
printTime("since it just started.");
}
~Stopwatch() { printTime("and is now stopping."); }
inline double elapsed()
{
std::chrono::time_point<std::chrono::high_resolution_clock> thisTime =
std::chrono::high_resolution_clock::now();
double deltaTime = std::chrono::duration<double, std::milli>(thisTime - start).count();
return deltaTime;
}
inline double elapsedLast()
{
std::chrono::time_point<std::chrono::high_resolution_clock> thisTime =
std::chrono::high_resolution_clock::now();
double deltaTime = std::chrono::duration<double, std::milli>(thisTime - last).count();
last = thisTime;
return deltaTime;
}
inline void printTime(std::string after = "")
{
std::stringstream s;
s << "Time in thread " << std::this_thread::get_id() << " is at " << std::setw(8) << std::fixed
<< std::setprecision(2) << elapsed() << "ms, " << std::fixed << std::setw(8) << elapsedLast()
<< "ms since last stopping. \"" << fromWhere << "\" " << after << '\n';
std::cout << s.str() << std::flush;
}
};