Skip to content

Instantly share code, notes, and snippets.

@chunkyguy
Created January 16, 2014 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chunkyguy/8457470 to your computer and use it in GitHub Desktop.
Save chunkyguy/8457470 to your computer and use it in GitHub Desktop.
/** 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