1
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

令我困惑的是,持续时间值与开始和结束时间不匹配。这两个日期仅相差微秒。是否有一个原因?

谢谢!

4

2 回答 2

2

localtime 返回一个静态分配的缓冲区,你调用它两次,所以 StartTime 和 EndTime 是相同的。您需要在每次调用后直接将其复制到另一个缓冲区中。

tm* startTime = localtime(&start.tv_sec); 
char buf[64]; 
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", startTime); 

tm* endTime = localtime(&end.tv_sec); 
char buf2[64]; 
strftime(buf2, sizeof(buf2), "%Y-%m-%d %H:%M:%S", endTime); 

编辑:你也可以这样写:

tm* pTimeBuf = localtime(&start.tv_sec); 
char buf[64]; 
strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", pTimeBuf); 

localtime(&end.tv_sec); // NB. I don't store th return value (since I have it already)
char buf2[64]; 
strftime(buf2, sizeof(buf2), "%Y-%m-%d %H:%M:%S", pTimeBuf); 
于 2012-05-16T00:30:57.863 回答
2

我同意 Edwin 的观点,只是稍作修改,最好使用线程安全版本localtime_r而不是 localtime

struct tm startTime,endTime;
memset(&startTime,0,sizeof(struct tm)); //Advisable but not necessary
memset(&endTime,0,sizeof(struct tm)); //Advisable but not necessary
localtime_r(&start.tv_sec, &startTime);
localtime_r(&end.tv_sec, &endTime);
于 2012-05-16T01:12:44.623 回答