Skip to content

Instantly share code, notes, and snippets.

@oschonrock
Created Dec 4, 2019
Embed
What would you like to do?
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

oschonrock 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_

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