We can find out the time taken by different parts of a program by using the std::chrono library introduced in C++ 11. We have discussed at How to measure time taken by a program in C. The functions described there are supported in C++ too but they are C specific. For clean and robust C++ programs we should strive to use C++ specific language constructs only.
std::chrono has two distinct objects–timepoint and duration. A timepoint as the name suggests represents a point in time whereas a duration represents an interval or span of time. The C++ library allows us to subtract two timepoints to get the interval of time passed in between. Using provided methods we can also convert this duration to appropriate units.
The std::chrono provides us with three clocks with varying accuracy. The high_resolution_clock is the most accurate and hence it is used to measure execution time.
Step 1: Get the timepoint before the function is called
Step 2: Get the timepoint after the function is called
Step 3: Get the difference in timepoints and cast it to required units
A complete C++ program demonstrating the procedure is given below. We fill up a vector with some random numbers and measure the time taken by sort() function to sort this vector.
Output: (Machine Dependent)
Time taken by function: 3062 microseconds
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Measure execution time with high precision in C/C++
- How to measure time taken by a function in C?
- Execution of printf with ++ operators
- RTTI (Run-time type Information) in C++
- C++ Program to print current Day, Date and Time
- Print system time in C++ (3 different ways)
- Cvent Interview Experience (On campus for Internship and Full Time)
- Amadeus Labs R & D | On Campus (freshers) | Full time+Internship
- Finding Median of unsorted Array in linear time using C++ STL
- Runtime and Compile-time constants in C++
- Program to convert time from 12 hour to 24 hour format
- What happens when a virtual function is called inside a non-virtual function in C++
- Function Overloading vs Function Overriding in C++
- Difference between Virtual function and Pure virtual function in C++
- How to call function within function in C or C++
- Difference between virtual function and inline function in C++
- Can we call an undeclared function in C++?
- Can we use function on left side of an expression in C and C++?
- Declare a C/C++ function returning pointer to array of integer pointers
- Function overloading and return type
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.