Skip to content

Instantly share code, notes, and snippets.

@srathi-monarch
Created October 20, 2023 09:58
Show Gist options
  • Save srathi-monarch/b3b53eb90839ae50661fdcdc02e8dc0e to your computer and use it in GitHub Desktop.
Save srathi-monarch/b3b53eb90839ae50661fdcdc02e8dc0e 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