我有这段代码:
struct timeval start, end;
gettimeofday(&start, NULL);
//code I'm timing
gettimeofday(&end, NULL);
long elapsed = ((end.tv_sec-start.tv_sec)*1000000 + end.tv_usec-start.tv_usec);
ofstream timeFile;
timeFile.open ("timingSheet.txt");
timeFile << fixed << showpoint;
timeFile << setprecision(2);
timeFile << "Duration: " << elapsed << "\n";
timeFile.close();
这将输出已经过去的微秒数。但是,如果我改变这一行
long elapsed = ((end.tv_sec-start.tv_sec)*1000000 + end.tv_usec-start.tv_usec);
对此:
long elapsed = ((end.tv_sec-start.tv_sec)*1000000 + end.tv_usec-start.tv_usec)/1000000.0;
我得到一个负值。为什么会这样?