Measure elapsed time of C++ program

Rajiv Ranjan Singh

Rajiv Ranjan Singh / February 22, 2022

1 min read––– views

Below C++ program calculates the time elapsed for a simple code in milliseconds, microseconds, nanoseconds, and seconds. It includes the <chrono.h> header which provides access to the current time using system_clock(). The system_clock() is designed to represent the real-time and used by all processes running on the system.

Code:

#include <iostream>
#include <chrono>
#include <unistd.h>

using namespace std;

int main() {
    auto start = chrono::steady_clock::now();

    sleep(2);

    auto end = chrono::steady_clock::now();

    cout << "Elapsed time in microseconds: "
         << chrono::duration_cast<chrono::microseconds>(end - start).count()
         << " µs" << endl;

    cout << "Elapsed time in milliseconds: "
         << chrono::duration_cast<chrono::milliseconds>(end - start).count()
         << " ms" << endl;

    cout << "Elapsed time in nanoseconds: "
         << chrono::duration_cast<chrono::nanoseconds>(end - start).count()
         << " ns" << endl;

    cout << "Elapsed time in seconds: "
         << chrono::duration_cast<chrono::seconds>(end - start).count()
         << " sec";

    return 0;
}

Output:

Elapsed time in microseconds: 2000127 µs
Elapsed time in milliseconds: 2000 ms
Elapsed time in nanoseconds: 2000127736 ns
Elapsed time in seconds: 2 sec