gpt4 book ai didi

ctime 没有正确获取循环开始/结束的时间差

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:09 25 4
gpt4 key购买 nike

我试图让一个循环在 executionTime 指定的准确时间执行。我正在使用 ctime 来获得这个时间,我需要它在几毫秒的精度内(我相信它是)。一旦该循环运行了指定的执行时间,它就会中断。

我的问题是执行时间为 0.5,打印的结果为 1。进一步测试后,我的程序似乎将执行时间四舍五入为最接近的整数。所以对于 4.5 executionTime,打印的执行时间是 5.0000000。我的代码如下。我不确定这个错误是从哪里来的。

#include <time.h> 
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
float executionTime = 4.5;
int i;
float timeDifference = -1;
time_t t1;
time_t t2;

t1 = time(0);

for (i = 0; i < 1000000000; i++)
{
t2 = time(0);

timeDifference = difftime(t2, t1);

if (timeDifference >= executionTime)
{
break;
}

}

printf("time difference is: %f\n", timeDifference);

return 0;

}

新版本尝试使用 clock_gettime。此版本存在在循环内由于某种原因达到执行时间时永不中断的问题。

#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

#define BILLION 1E9

int main()
{
float executionTime = 4.5;
int i;
float elapsedTime = -1;

struct timespec start;
struct timespec stop;

//Get starting time
clock_gettime(CLOCK_REALTIME, &start);

for (i = 0; i < 1000000000; i++)
{
//Get current time
clock_gettime(CLOCK_REALTIME, &stop);

elapsedTime = ((stop.tv_sec - start.tv_sec) + (stop.tv_nsec - start.tv_nsec)) / BILLION;

if (elapsedTime >= executionTime)
{
break;
}
}

printf("time difference is: %f\n", elapsedTime);

return 0;

}

最佳答案

clock_gettime 可用于获得更高的准确性。
使用大于 0 的值调用 delay 以设置延迟时间,然后使用 -1 检查耗时。
在 main 中调用 clock_gettime 将在 main 中给出耗时。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <time.h>

#define BILLION 1E9

int delay ( double seconds)
{
static double usec = 0.0;
double elapsed = 0.0;
static struct timespec start;
struct timespec stop;

if ( 0.0 <= seconds) {
usec = seconds;
clock_gettime ( CLOCK_REALTIME, &start);
return 0;
}
clock_gettime ( CLOCK_REALTIME, &stop);
elapsed = difftime ( stop.tv_sec, start.tv_sec);
elapsed += ( stop.tv_nsec - start.tv_nsec) / BILLION;
if ( ( elapsed < usec)) {
return 1;
}
return 0;
}

int main() {

double executionTime = 4.5;
int i;
double timeDifference = -1;
struct timespec end;
struct timespec begin;

clock_gettime ( CLOCK_REALTIME, &begin);
delay( executionTime);//call to set time

for (i = 0; i < 1000000000; i++)
{
if ( !delay( -1)) {//call to check elapsed time
break;
}
}
clock_gettime ( CLOCK_REALTIME, &end);
timeDifference = difftime ( end.tv_sec, begin.tv_sec);
timeDifference += ( end.tv_nsec - begin.tv_nsec) / BILLION;

printf("time difference is: %f\n", timeDifference);

return 0;
}

关于ctime 没有正确获取循环开始/结束的时间差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54678092/

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