C++ Scoped Timer
Code for scoped timer. Once a block goes out of a scope, duration will be printed.
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
#include <iostream>
#include <string>
#include <chrono>
struct ScopedTimer {
std::chrono::steady_clock::time_point m_begin;
std::string m_name;
ScopedTimer(const std::string& name) : m_begin{std::chrono::steady_clock::now()}, m_name{name} {
std::cout << '[' << m_name << "] Starts...\n";
}
~ScopedTimer() {
auto end = std::chrono::steady_clock::now();
std::cout << '[' << m_name << "] Time difference (sec) = "
<< (std::chrono::duration_cast<std::chrono::microseconds>(end - m_begin).count()) / 1'000'000.0
<< std::endl;
}
};
auto main() -> int {
{
ScopedTimer t{"Foo"};
// some code
}
return 0;
}
This post is licensed under CC BY 4.0 by the author.