Measuring runtime in milliseconds using the C++ 11 chrono library

I have been playing around with the new C++ 11 standard. It includes a nice new library called chrono which includes some useful clocks and timers. Below is an example of some macros you can use to time your applications in milliseconds and print out the result. Timing can be turned off by removing the #define TIMING line. Remember to compile the program with C++11 (or C++0x) enabled. For GCC this should be:

g++ main.cpp -std=c++0x
#include <iostream>
#include <chrono>
 
#define TIMING
 
#ifdef TIMING
#define INIT_TIMER auto start = std::chrono::high_resolution_clock::now();
#define START_TIMER  start = std::chrono::high_resolution_clock::now();
#define STOP_TIMER(name)  std::cout << "RUNTIME of " << name << ": " << \
    std::chrono::duration_cast<std::chrono::milliseconds>( \
            std::chrono::high_resolution_clock::now()-start \
    ).count() << " ms " << std::endl; 
#else
#define INIT_TIMER
#define START_TIMER
#define STOP_TIMER(name)
#endif
 
int main() {
    INIT_TIMER
    START_TIMER
    sleep(2);
    STOP_TIMER("sleeping for 2 seconds")
    START_TIMER
    long unsigned int b = 0;
    for(int i = 0; i < 10000000; i++) {
        b += i;
    }
    STOP_TIMER("some long loop")
}

Example output:

RUNTIME of sleeping for 2 seconds: 2000 ms 
RUNTIME of some long loop: 24 ms 

You may also like...

2 Responses

  1. Anonymous says:

    WWWWWWWWWWWWWHHHHHHHHHHHHHHYYYYYYYYYYYYYYY the #defines?!!?

  2. Xmiler says:

    Good point.
    I would also offer the possibility of discounting timing (for example in the loop):

    #define INIT_TIMER_GAP auto start_gap = std::chrono::high_resolution_clock::now();
    #define START_TIMER_GAP start_gap = std::chrono::high_resolution_clock::now();
    #define INIT_TIMER_GAP_ITEM(item_name) chrono::duration item_name;
    #define INCREASE_TIMER_GAP_ITEM(item_name) item_name += std::chrono::high_resolution_clock::now() – start_gap;
    #define RESET_TIMER_GAP_ITEM(item_name) item_name = chrono::duration::zero();

Leave a Reply

Your email address will not be published.