Last active
October 28, 2021 10:36
-
-
Save mbitsnbites/c2f036275df3cd9fe19f9253235d2822 to your computer and use it in GitHub Desktop.
A minimalist C++11 performance measurement helper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <chrono> | |
#include <iostream> | |
/// @brief Scoped performance measurement class. | |
/// | |
/// To use this class, instantiate a @c perf_t object inside a scope. Once the | |
/// object goes out of scope, the elapsed time (in nanoseconds) will be printed | |
/// to stdout. | |
/// | |
/// @code{.cpp} | |
/// void my_function() { | |
/// perf_t perf("my_function"); | |
/// ... | |
/// // The elapsed time will be printed here. | |
/// } | |
/// @endcode | |
class perf_t { | |
public: | |
/// @brief Constructor (start time measurement). | |
/// @param name The name of the perf point. | |
explicit perf_t(const std::string& name) | |
: m_name(name), m_start(std::chrono::high_resolution_clock::now()) {} | |
/// @brief Destructor (print elapsed time). | |
~perf_t() { | |
const auto end = std::chrono::high_resolution_clock::now(); | |
const auto dt_ns = | |
std::chrono::duration_cast<std::chrono::nanoseconds>(end - m_start) | |
.count(); | |
std::cout << m_name << ": " << dt_ns << " ns\n"; | |
} | |
private: | |
const std::string m_name; | |
const std::chrono::high_resolution_clock::time_point m_start; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment