Skip to content

Instantly share code, notes, and snippets.

@surajRathi
Forked from srathi-monarch/time_it.hpp
Created October 23, 2023 11:06
Show Gist options
  • Save surajRathi/7c4db1f4e0ab1f8ba69b4cc8195e16a1 to your computer and use it in GitHub Desktop.
Save surajRathi/7c4db1f4e0ab1f8ba69b4cc8195e16a1 to your computer and use it in GitHub Desktop.
Simple scope based code execution time printer.
#include <chrono>
#include <iostream>
#include <string>
class TimeIt {
private:
std::string m_name;
std::chrono::time_point<std::chrono::high_resolution_clock> m_beg;
public:
explicit TimeIt(std::string name) : m_name(std::move(name)), m_beg(std::chrono::high_resolution_clock::now()) {
std::cout << m_name << ": Starting" << std::endl;
}
~TimeIt() {
auto end = std::chrono::high_resolution_clock::now();
// Timings in release are on a different scale.
#ifdef NDEBUG
auto dur = std::chrono::duration_cast<std::chrono::milliseconds>(end - m_beg);
std::cout << m_name << ": " << dur.count() << " ms" << std::endl;
#else
auto dur = std::chrono::duration_cast<std::chrono::seconds>(end - m_beg);
std::cout << m_name << ": " << dur.count() << " s" << std::endl;
#endif
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment