轻松测量经过的时间
问题:
使用以下命令测量程序中经过的时间time(),为什么之前和之后的值可能仍然是相同?
解释:
time() 返回自纪元以来的当前时间(以秒为单位)。如果要测量的时间跨度很短,前后值之间的差异可能会太小而无法检测到。
解决方案:
要准确测量短时间时间跨度,考虑使用替代方法:
C 结构化时间测量:
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 风格精确时间测量:
#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;
以上是为什么'time()”有时在短任务之前和之后返回相同的值?的详细内容。更多信息请关注PHP中文网其他相关文章!