Skip to content

Instantly share code, notes, and snippets.

@oschonrock
Created December 4, 2019 20:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oschonrock/e54612fe634f98a61376279dde3b0ac9 to your computer and use it in GitHub Desktop.
Save oschonrock/e54612fe634f98a61376279dde3b0ac9 to your computer and use it in GitHub Desktop.
C++ Basic profiling timer class
class Timer
{
public:
Timer(std::string label_) : start{std::chrono::high_resolution_clock::now()}, label{label_} {};
~Timer() { print(); }
void print() {
finish = std::chrono::high_resolution_clock::now();
auto elapsed_ms = std::chrono::duration_cast<std::chrono::duration<double>>(finish - start).count() * 1000;
std::cout << label << "=" << elapsed_ms << "ms\n";
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start, finish;
std::string label;
};
@ranoke
Copy link

ranoke commented Nov 15, 2021

line 4: best practice is not to copy std::string label_ and rather take it by ref like this: const std::string& label_

@oschonrock
Copy link
Author

line 4: best practice is not to copy std::string label_ and rather take it by ref like this: const std::string& label_

Thanks. Yes, that's fair comment. This is actually a very old version of that code.

More up to date version here:
https://github.com/oschonrock/toolbelt/blob/master/os/bch.hpp

Which uses "pass by value and then move" - because we want our own copy of the label - but avoids the double copy which, as you point out, the above code is doing.

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