1. Use the <chrono> library (C++11 and later versions)
<chrono>
The library provides high-precision time measurement functions.
#include <iostream> #include <chrono> int main() { auto start = std::chrono::high_resolution_clock::now(); // Your code here // ... auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(stop - start).count(); std::cout << "Elapsed time: " << duration << " ms\n"; return 0; }
2. Use the <ctime> library (older but commonly used method)
<ctime>
The library provides a function clock() based on system time.
#include <iostream> #include <ctime> int main() { clock_t start = clock(); //You can also double start = clock(); // Your code here // ... clock_t end = clock(); double cpu_time_used = static_cast<double>(end - start) / CLOCKS_PER_SEC; // /CLOCKS_PER_SEC converts the result into units of seconds std::cout << "CPU time used: " << cpu_time_used << " s\n"; return 0; }
3. Use third-party libraries (such as)
The Boost library provides a timer module for measuring the execution time of a code block.
First, you need to install the Boost library and include the header file in your project.
#include <boost/timer/> #include <iostream> int main() { boost::timer::auto_cpu_timer t; // Automatic measurement and printing execution time // Your code here // ... return 0; }
4. Use Windows API functions (specific to Windows platform)
4.1 Use GetTickCount()
This function returns the number of milliseconds elapsed from system startup.GetTickCount()
The accuracy is between 1 and 15 milliseconds, and its value will be reversed after about 49.7 days.
#include <> #include <iostream> int main() { DWORD start = GetTickCount(); // ... Execute your code ... DWORD end = GetTickCount(); std::cout << "Program run time: " << (end - start) << "Milliseconds" << std::endl; return 0; }
4.2 Use QueryPerformanceCounter() and QueryPerformanceFrequency()
These two functions provide higher precision, usually at the microsecond level.
#include <> #include <iostream> int main() { LARGE_INTEGER start, end, freq; QueryPerformanceFrequency(&freq); QueryPerformanceCounter(&start); // ... Execute your code ... QueryPerformanceCounter(&end); double elapsedTime = (double)( - ) / * 1000.0; // milliseconds std::cout << "Program run time: " << elapsedTime << "Milliseconds" << std::endl; return 0; }
This is the end of this article about four methods of recording program runtime in C++. For more related C++ program runtime content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!