Easily Measure Elapsed Time
Question:
When measuring time elapsed in a program using time(), why might the before and after values remain the same?
Explanation:
time() returns the current time in seconds since the Epoch. If the time span to be measured is short, the difference between the before and after values may be too small to be detected.
Solution:
To accurately measure short time spans, consider using alternative methods:
C Structured Time Measurement:
struct timeval startTV, endTV; gettimeofday(&startTV, NULL); // Execute time-consuming tasks gettimeofday(&endTV, NULL); timersub(&endTV, &startTV, &diff); printf("**time taken = %ld %ld\n", diff.tv_sec, diff.tv_usec);
C 11 Style Precision Time Measurement:
#include <chrono> std::chrono::steady_clock::time_point begin = std::chrono::steady_clock::now(); // Execute time-consuming tasks std::chrono::steady_clock::time_point end = std::chrono::steady_clock::now(); std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::microseconds>(end - begin).count() << "[µs]" << std::endl; std::cout << "Time difference = " << std::chrono::duration_cast<std::chrono::nanoseconds>(end - begin).count() << "[ns]" << std::endl;
The above is the detailed content of Why Does `time()` Sometimes Return the Same Value Before and After a Short Task?. For more information, please follow other related articles on the PHP Chinese website!