Skip to content

Instantly share code, notes, and snippets.

@maneesh29s
Last active April 12, 2024 12:39
Show Gist options
  • Select an option

  • Save maneesh29s/b9881add1c132d7e585ccab034e07593 to your computer and use it in GitHub Desktop.

Select an option

Save maneesh29s/b9881add1c132d7e585ccab034e07593 to your computer and use it in GitHub Desktop.
Timer class. Takes std::chrono::type as template for timer unit
template <typename T>
class Timer {
private:
std::chrono::time_point<std::chrono::high_resolution_clock> start;
std::chrono::time_point<std::chrono::high_resolution_clock> end;
public:
void start_timer() {
this->start = std::chrono::high_resolution_clock::now();
}
void stop_timer() {
this->end = std::chrono::high_resolution_clock::now();
}
std::string time_elapsed() {
auto time_taken = std::chrono::duration_cast<T>(this->end - this->start).count();
std::string unit = "";
if (std::is_same<T, std::chrono::seconds>::value)
unit = "s";
else if (std::is_same<T, std::chrono::milliseconds>::value)
unit = "ms";
else if (std::is_same<T, std::chrono::microseconds>::value)
unit = "us";
else if (std::is_same<T, std::chrono::nanoseconds>::value)
unit = "ns";
return std::to_string(time_taken) + " " + unit;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment