【问题标题】:Is this an overflow?这是溢出吗?
【发布时间】:2012-05-15 20:13:00
【问题描述】:

我有这段代码:

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;

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

【问题讨论】:

  • 你能用使用的语言标记这个问题吗?
  • 看起来像 C++,但如果我错了,请纠正我。
  • endstart的值是什么导致负值?
  • 请添加一些导致问题的示例值。否则我们只能猜测。

标签: c++ double long-integer


【解决方案1】:

您将除以一个双精度数:1000000.0,然后转换回整数类型。

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

试试:

double elapsed = (double)(end.tv_sec-start.tv_sec) + (double)(end.tv_usec-start.tv)/1000000.0;

【讨论】:

  • OP 暗示第一种形式(没有除法)没有给出负值,但第二种形式......
  • 第二种形式的结果是double数据类型;但他将其存储在long 变量中。因为他没有强制转换 C++ 将其视为结果中的数据明确地是elapsed 中的数据,对吧?因此他很可能会得到一个奇怪的数字。
  • long x = (blah / 1000000.0)long x = (long)(blah / 1000000.0) 相同。
  • 我把它改成了这样:long elapsed = ((double)(end.tv_sec-start.tv_sec) + (double)(end.tv_usec-start.tv_usec))/100000.0;,我仍然得到一个负值。
  • 该代码会生成警告:codepad.org/kGsGt7LB 我很容易出错,但我认为您想要double elapsed
【解决方案2】:

我使用了从 SO 上某处借来的计时类。

#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

对于我的hash function project,我得到:

Number of collisions: 0
Set size: 16777216
VM: 841.797MB
22.5810500000 seconds

【讨论】:

  • 我知道这并不能回答问题,但它提供了解决问题的方法。
  • 谢谢!这将对未来有所帮助。
  • 我得到了 -.101 我认为这可能与我正在使用的设备有关。
  • 如果我没记错的话,这个类是为 Linux(和 * UNIX)设计的,因为典型的 Windows 实现以毫秒级别记录时间。
猜你喜欢
  • 2015-06-09
  • 2012-11-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-16
  • 1970-01-01
  • 2021-02-24
  • 1970-01-01
相关资源
最近更新 更多