Created
January 16, 2014 16:01
-
-
Save chunkyguy/8457470 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** Log execution time of a block of code in nanoseconds and milliseconds | |
* Just add a Timer object at the start of the code block. | |
* Provide a prefix string about some context | |
* | |
* Example: | |
* long LargestPrimeFactor(const long num) | |
* { | |
* Timer t("LargestPrimeFactor:(" + std::to_string(num) + ") "); | |
* //stuff here.. | |
* } | |
* | |
* Output: | |
* LargestPrimeFactor:(13195) 718315 ns 0ms | |
*/ | |
#include <iostream> | |
#include <chrono> | |
#include <string> | |
class Timer { | |
public: | |
Timer(const std::string &pre) : | |
start(std::chrono::high_resolution_clock::now()), | |
prefix(pre) | |
{} | |
~Timer() | |
{ | |
std::chrono::time_point<std::chrono::high_resolution_clock> end = std::chrono::high_resolution_clock::now(); | |
std::chrono::nanoseconds dt = end - start; | |
std::cout << prefix << dt.count() << " ns " | |
<< std::chrono::duration_cast<std::chrono::milliseconds>(dt).count() << "ms" | |
<< std::endl; | |
} | |
private: | |
std::chrono::time_point<std::chrono::high_resolution_clock> start; | |
std::string prefix; | |
}; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment