0

我有这段代码:

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;

我得到一个负值。为什么会这样?

4

2 回答 2

1

您正在除以 double: 1000000.0,然后重新转换为整数类型。

假设你所有的开始和结束变量都是整数(或长整数),有一个尴尬的转换成双精度数,然后再转换成一个长整数。

尝试:

double elapsed = (double)(end.tv_sec-start.tv_sec) + (double)(end.tv_usec-start.tv)/1000000.0;
于 2012-05-15T20:21:14.877 回答
1

我使用我从这里某处借来的计时课程。

#include <time.h>
#include <sys/time.h>
#include <iomanip>
#include <iostream>

using namespace std;

class Timer 
{
private:

timeval startTime;

public:

  void start()
  {
    gettimeofday(&startTime, NULL);
  }

  double stop()
  {
    timeval endTime;
    long seconds, useconds;
    double duration;

    gettimeofday(&endTime, NULL);

    seconds  = endTime.tv_sec  - startTime.tv_sec;
    useconds = endTime.tv_usec - startTime.tv_usec;

    duration = seconds + useconds/1000000.0;

    return duration;
  }

  static void printTime(double duration)
  {
    cout << setprecision(6) << fixed << duration << " seconds" << endl;
  }
};

例如:

Timer timer = Timer();
timer.start();
long x=0;
for (int i = 0; i < 256; i++)
  for (int j = 0; j < 256; j++)
    for (int k = 0; k < 256; k++)
      for (int l = 0; l < 256; l++)
        x++;
timer.printTime(timer.stop());

产量11.346621 seconds

对于我的哈希函数项目,我得到:

Number of collisions: 0
Set size: 16777216
VM: 841.797MB
22.5810500000 seconds
于 2012-05-15T20:41:14.707 回答