簡體   English   中英

Linux中的clock_gettime

[英]clock_gettime in Linux

MAIN.c:

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

您的tv_nsec乘數是錯誤的,而常量BILLION也是錯誤的。 前綴n (nano)表示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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM