In this post, we will discuss how to measure elapsed time of a C++ program in seconds, milliseconds, microseconds and nanoseconds using chrono library.
Since C++11, the best way to measure elapsed time in C++ is by using the chrono library which deal with time.
Below 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
Related Post: Find the execution time of a C program
Thanks for reading.
Please use our online compiler to post code in comments. To contribute, get in touch with us.
Like us? Please spread the word and help us grow. Happy coding 🙂
Leave a Reply
yaaaaaa