Measure elapsed time of a C++ program using Chrono library
This post will discuss how to measure the elapsed time of a C++ program in seconds, milliseconds, microseconds, and nanoseconds using the Chrono library.
Since C++11, the best way to measure elapsed time in C++ is by using the Chrono library, which deals with time.
Following C++ program calculates the time elapsed for a simple code in seconds, milliseconds, microseconds, and nanoseconds. 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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
#include <iostream> #include <chrono> #include <unistd.h> using namespace std; // Main function to measure elapsed time of a C++ program // using Chrono library int main() { auto start = chrono::steady_clock::now(); // do some stuff here sleep(3); auto end = chrono::steady_clock::now(); cout << "Elapsed time in nanoseconds: " << chrono::duration_cast<chrono::nanoseconds>(end - start).count() << " ns" << endl; 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 seconds: " << chrono::duration_cast<chrono::seconds>(end - start).count() << " sec"; return 0; } |
Output (may vary):
Elapsed time in nanoseconds: 3000090354 ns
Elapsed time in microseconds: 3000090 µs
Elapsed time in milliseconds: 3000 ms
Elapsed time in seconds: 3 sec
That’s all about measuring elapsed time of a C++ program using the Chrono library.
Related Post:
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)