gpt4 book ai didi

Linux 中的时钟获取时间

转载 作者:行者123 更新时间:2023-11-30 17:36:34 24 4
gpt4 key购买 nike

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);
}

定时器.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(纳米)表示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
}

关于Linux 中的时钟获取时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22628644/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com