Skip to content

Instantly share code, notes, and snippets.

@Bktero
Last active May 25, 2018 07:45
Show Gist options
  • Save Bktero/b5a31fe147bb9183205aded078d228d6 to your computer and use it in GitHub Desktop.
Save Bktero/b5a31fe147bb9183205aded078d228d6 to your computer and use it in GitHub Desktop.
[C++11] How to measure elapsed time
#include <chrono>
#include <iostream>
#include <thread> // to get sleep_for()
/**
* How to measure elapsed time in C++11.
*
* It uses 'steady_clock' because it is monotonic. Being monotonic means that it cannot decrease so it is the most suitable clock
* for time measurements.
*
* @see http://en.cppreference.com/w/cpp/chrono
*/
std::chrono::milliseconds MAX_DURATION(50);
int main() {
std::chrono::time_point<std::chrono::steady_clock> start = std::chrono::steady_clock::now();
std::this_thread::sleep_for(std::chrono::milliseconds(100)); // simulate execution of something to measure
std::chrono::time_point<std::chrono::steady_clock> stop = std::chrono::steady_clock::now();
std::chrono::duration<double, std::milli> elapsed = stop - start;
std::cout << "Elapsed: " << elapsed.count() << " ms" << std::endl;
if (elapsed > MAX_DURATION) {
std::cout << "Too long!" << std::endl;
}
}
/**
* It is possible to simplify the code with 'using' directives.
* It is also possible to use 'auto' ;)
*/
using namespace std::chrono;
using Clock = steady_clock;
using TimePoint = time_point<Clock>;
using Milliseconds = milliseconds;
using Duration = duration<double, std::milli>;
Elapsed: 99.5516 ms
Too long!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment