2014-03-25 18 views
0

MAIN.C:clock_gettime在Linux中

int sum() 
{ 
    int x = 100, y =200, z; 
    z =x; 
    z=y; 
    printf("value is %d", z); 
    return 1; 

} 

int main() 
{ 
    double starttime, stoptime; 
    int a=1, b=10, c; 
    starttime = GetTimeStamp();   // I am calculating time here. 
    printf("start time is %f", starttime); 
    c =a; 
    printf("value is %d", c); 
    c =b; 
    printf("value is %d", c); 
    c= a+b; 

     printf("value is %d", c); 
     printf("value is %d", c); 
     printf("value is %d", c); 
     printf("value is %d", c);  

    stoptime =GetTimeStamp(); // I want to know the time here. 
    printf("stop time is %f", stoptime); 
    return 0; 

} 

timer.c中:

#define BILLION 1000000L 
typedef unsigned int uint32_t; 

int GetTimeStamp() 
{ 
struct timespec start; 

//double startTime; 

      // if((startTime = clock_gettime(CLOCK_REALTIME, &start)) == -1) 
      if((clock_gettime(CLOCK_REALTIME, &start)) == -1) 
      { 
       perror("clock gettime"); 

      } 
     // startTime =start.tv_sec + 0.0000001 * start.tv_nsec; // to make it milli 


     return ((start.tv_sec + 0.0000001 * start.tv_nsec)/(double)BILLION); 
} 

timer.h:

#ifndef TIMESTAMP_H_ 
#define TIMESTAMP_H_ 
int GetTimeStamp(); 

#endif /* TIMESTAMP_H_ */ 

我想創建一個自由運行的定時器,並希望獲取開始執行的時間以及完成執行的時間。所以我在TIMER.c中創建了一個定時器,我在main.c中使用了它。我在程序開始時在MAIN.c中調用GetTimeStamp(),並在時間結束時再次調用它。輸出:它顯示的啓動時間和停止時間都是相同的1594.0000000

+1

您可能想要檢查'GetTimeStamp'函數的返回類型。 –

回答

0

您的乘數爲tv_nsec是錯誤的,而您的常數BILLION也是錯誤的。前綴n(納米)表示10^-9,十億等於10^9。變化:

return ((start.tv_sec + 0.0000001 * start.tv_nsec)/(double)BILLION); 

到:

return 1e9 * start.tv_sec + start.tv_nsec;  // return ns time stamp 

或:

return 1e6 * start.tv_sec + start.tv_nsec * 1e-3; // return µs time stamp 

或:

return 1e3 * start.tv_sec + start.tv_nsec * 1e-6; // return ms time stamp 

或:

return start.tv_sec + start.tv_nsec * 1e-9;  // return seconds time stamp 

取決於您想要用於時間戳的單位。

正如其他地方已經指出的那樣,您可能想要使用例如一個double爲您的時間戳,而不是一個int,因爲這給你更好的範圍和分辨率,這也是你在main已經使用的。

double GetTimeStamp(void) 
{ 
    ... 

    return 1e9 * start.tv_sec + start.tv_nsec;  // return ns time stamp 
} 
+0

萬謝謝你。 – user3458454

+0

如果我正在爲實時linux做同樣的事情,那我可以使用相同的API嗎? – user3458454

+0

當然''clock_gettime'是非常標準的 - 唯一需要注意的是(a)並非所有的時鐘類型都支持所有平臺,並且(b)某些時鐘類型返回CPU時間和一些返回掛鐘時間 - 這可能很重要很多,例如如果你使用線程。 –

相關問題