Last active
June 14, 2022 18:21
-
-
Save bolry/b3458d8c58c7f2db8fbef337fdb36ea1 to your computer and use it in GitHub Desktop.
C++11 Stopwatch
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Stopwatch { | |
using clock = std::chrono::high_resolution_clock; | |
bool is_running() const { return stop_time_ == clock::time_point::min(); } | |
clock::time_point end_time() const { return is_running() ? clock::now() : stop_time_; } | |
clock::time_point begin_time_{clock::now()}, stop_time_{clock::time_point::min()}; | |
public: | |
void stop() { if (is_running()) stop_time_ = clock::now(); } | |
clock::duration elapsed() const { return end_time() - begin_time_; } | |
}; | |
std::ostream& operator<<(std::ostream& os, Stopwatch const& stopwatch) | |
{ | |
auto e = std::chrono::duration<double, std::micro>(stopwatch.elapsed()); | |
auto oldLoc = std::cout.imbue(std::locale("")); | |
std::cout << e.count() << " microseconds\n"; | |
std::cout.imbue(oldLoc); | |
return os; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I think the
operator<<
implementation should be using "os" (std::ostream
) parameter instead ofstd::cout
?