Skip to content

Instantly share code, notes, and snippets.

@bolry
Last active June 14, 2022 18:21
Show Gist options
  • Save bolry/b3458d8c58c7f2db8fbef337fdb36ea1 to your computer and use it in GitHub Desktop.
Save bolry/b3458d8c58c7f2db8fbef337fdb36ea1 to your computer and use it in GitHub Desktop.
C++11 Stopwatch
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;
}
@S3riousSam
Copy link

I think the operator<< implementation should be using "os" (std::ostream) parameter instead of std::cout?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment