Commit 62a2182f authored by Nguyen, Thien's avatar Nguyen, Thien
Browse files

Added a util scope timer class


Signed-off-by: Nguyen, Thien's avatarThien Nguyen <nguyentm@ornl.gov>
parent 02a9aaae
......@@ -310,4 +310,25 @@ void XACCLogger::error(const std::string &msg, MessagePredicate predicate) {
}
}
ScopeTimer::ScopeTimer(const std::string& scopeName, bool shouldLog):
m_startTime(std::chrono::system_clock::now()),
m_shouldLog(shouldLog),
m_scopeName(scopeName)
{
if (m_shouldLog) {
XACCLogger::instance()->info("'" + scopeName + "' started.");
}
}
double ScopeTimer::getDurationMs() const {
return static_cast<double>(
std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now() - m_startTime).count()/1000.0);
}
ScopeTimer::~ScopeTimer() {
const double elapsedTime = getDurationMs();
if (m_shouldLog) {
XACCLogger::instance()->info("'" + m_scopeName + "' finished [" + std::to_string(elapsedTime) + " ms].");
}
}
} // namespace xacc
......@@ -21,6 +21,7 @@
#include <sstream>
#include <algorithm>
#include <map>
#include <chrono>
namespace spdlog {
class logger;
......@@ -233,6 +234,40 @@ template <typename T> std::vector<T> linspace(T a, T b, size_t N) {
return xs;
}
// Util timer to log execution elapsed time of a scope block.
// Example usage:
// (1) Time a function body:
/*
void slowFunc {
// Use __FUNCTION__ macro to get the function name
// Can use a custom string as well
ScopeTimer timer(__FUNCTION__);
.... code
}
*/
// The above timer will log when the function starts and ends (with elapsed time).
// (2) Time a code block, including function calls
/*
... irrelevant code
// Create a scope block:
{
ScopeTimer timer("human readable name of this block");
.... code
}
... irrelevant code
*/
// This will log the timing data of that specific code block.
class ScopeTimer {
public:
ScopeTimer(const std::string& scopeName, bool shouldLog = true);
double getDurationMs() const;
~ScopeTimer();
private:
std::chrono::time_point<std::chrono::system_clock> m_startTime;
bool m_shouldLog;
std::string m_scopeName;
};
// container helper
namespace container {
template<typename ContainerType, typename ElementType>
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment