Determining the precise execution time of code snippets in C is essential for performance analysis and optimization. However, the standard clock() function may fall short for measuring brief code segments, often returning "0 seconds."
To address this limitation, a more accurate approach is to utilize the GetTimeMs64() function, which measures elapsed time in milliseconds since the UNIX epoch, regardless of the platform (Windows or Linux).
#include <ctime> #include <chrono> uint64_t GetTimeMs64() { return std::chrono::duration_cast<std::chrono::milliseconds>( std::chrono::system_clock::now().time_since_epoch() ).count(); }
GetTimeMs64() provides a high level of precision, with a granularity of 1 millisecond on most platforms.
To calculate the execution time of a code snippet, follow these steps:
uint64_t startTime = GetTimeMs64(); // Execute the code snippet uint64_t endTime = GetTimeMs64(); double executionTime = static_cast<double>(endTime - startTime) / 1000.0;
The executionTime variable now contains the duration of the code snippet in seconds, with high precision.
The above is the detailed content of How Can I Accurately Measure the Execution Time of Short C Code Snippets?. For more information, please follow other related articles on the PHP Chinese website!