【发布时间】:2012-05-23 13:02:52
【问题描述】:
struct timeval start, end, duration;
gettimeofday(&start, NULL);
res = curl_easy_perform(curl);
gettimeofday(&end, NULL);
timersub(&end, &start, &duration);
tm* startTime = localtime(&start.tv_sec);
tm* endTime = localtime(&end.tv_sec);
char buf[64];
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", startTime);
char buf2[64];
strftime(buf2, sizeof(buf2), "%Y-%m-%d %H:%M:%S", endTime);
ofstream timeFile;
timeFile.open ("timingSheet.txt");
timeFile << fixed << showpoint;
timeFile << setprecision(6);
timeFile << "Duration: " << duration.tv_sec << "." << duration.tv_usec << " seconds \n";
timeFile << "Start time: " << buf <<"." << start.tv_usec << "\n";
timeFile << "End time: " << buf2 <<"." << end.tv_usec << "\n";
timeFile.close();
当我运行这段代码时,我得到了这个输出:
Duration: 3.462243 seconds
Start time: 2012-05-15 17:14:07.432613
End time: 2012-05-15 17:14:07.894856
令我困惑的是,持续时间值与开始和结束时间不匹配。这两个日期仅相差微秒。是否有一个原因?
谢谢!
【问题讨论】:
-
timersub()会发生什么? -
timersub() 不应影响开始或结束。它只是一个获取两个 timeval 的差异并将这些值放在 duration 中的函数。
-
请贴出代码。如果它不改变
start或end,那么它一定会错误地计算duration。 -
linux.die.net/man/3/timersub 我不确定代码实际在哪里。
-
# define timersub(a, b, result) \ do { \ (result)->tv_sec = (a)->tv_sec - (b)->tv_sec; \ (result)->tv_usec = (a)->tv_usec - (b)->tv_usec; \ if ((result)->tv_usec < 0) { \ --(result)->tv_sec; \ (result)->tv_usec += 1000000; \ } \ } while (0) #endif /* BSD */
标签: c++ timing strftime timeval