Skip to content

Instantly share code, notes, and snippets.

@wutipong
Last active September 3, 2015 16:25
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 wutipong/277b9d1c668c2a23c832 to your computer and use it in GitHub Desktop.
Save wutipong/277b9d1c668c2a23c832 to your computer and use it in GitHub Desktop.
Simple time measurement class. Useful for finding how long a function/a scope runs.
#include <iostream>
#include <array>
#include <chrono>
#include <string>
#include <ctime>
#include <cstdlib>
class timer {
private:
const std::chrono::system_clock::time_point start;
const std::string functionName;
std::ostream &stream;
public:
timer(const std::string &_f, std::ostream &_s = std::cout)
: start(std::chrono::system_clock::now()), functionName(_f), stream(_s) {}
timer(std::ostream &_s = std::cout)
: start(std::chrono::system_clock::now()), stream(_s),
functionName("<unknown>"){};
~timer() {
auto end = std::chrono::system_clock::now();
stream << functionName << " took "
<< std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
.count()
<< "ms." << std::endl;
}
};
int function();
int main(char **, int) {
function();
system("pause");
}
int function() {
timer t(__FUNCTION__);
std::srand(time(0));
for (int i = 0; i < 1000000; i++) {
int rand = std::rand() % 1000;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment