2012-05-15 30 views
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; 

我得到一個負值。爲什麼會發生?

+0

能否請您與標籤所使用的語言這個問題? – bdukes

+0

看起來像C++,但糾正我,如果我錯了。 – mc10

+0

導致負值的'end'和'start'的值是多少? –

回答

1

您將除以雙:1000000.0,並重新轉換爲整數類型。

假定你所有的開始和結束變量都是整數(或長整數),那麼就會有一個笨拙的投入到double中,然後回到long中。

嘗試:

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

該OP是暗示第一種形式(沒有除法)不會給出負值,但第二種形式是... –

+0

第二種形式將有一個結果作爲'double'數據類型;但他將其存儲在一個「長」變量中。因爲他沒有將C++視爲模仿它,就好像結果中的數據顯式是'elapsed'中的數據,對吧?因此他可能會得到一個奇怪的數字。 –

+0

'long x =(blah/1000000.0)'與'long x =(long)(blah/1000000.0)'相同。 –

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

對於我hash function project,我得到:

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

我知道這並不回答這個問題,但它提供瞭解決問題的方法。 – Drise

+0

謝謝!這將對未來有所幫助。 – Dave

+0

其實這並沒有奏效。 – Dave