gpt4 book ai didi

Clock_Gettime() 抖动?

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

我在 Linux 2.6 上使用 clock_gettime()(来自 time.h)来控制线程循环中的计时。我需要在 +/- 5mS 时间范围内有 500mS。它似乎给了我 500 毫秒,然后开始漂移或抖动到 +/- 30 毫秒:

enter image description here

我正在使用 CLOCK_REALTIME 调用它。有什么方法可以改善它的偏差吗?我只是用它计算每个毫秒,一旦计数器达到 500,就会触发中断。

这也在 QT 4.3 框架内。 QTimer 似乎比这更紧张。

最佳答案

根据您问题的措辞,我感觉您可能错误地计算了时差。

试试这个方法:

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

long elapsed_milli( struct timespec * t1, struct timespec *t2 )
{
return (long)(t2->tv_sec - t1->tv_sec) * 1000L
+ (t2->tv_nsec - t1->tv_nsec) / 1000000L;
}

int main()
{
const long period_milli = 500;
struct timespec ts_last;
struct timespec ts_next;
const struct timespec ts_sleep = { 0, 1000000L };

clock_gettime( CLOCK_REALTIME, &ts_last );

while( 1 )
{
nanosleep( &ts_sleep, NULL );
clock_gettime( CLOCK_REALTIME, &ts_next );
long elapsed = elapsed_milli( &ts_last, &ts_next );

if( elapsed >= period_milli )
{
printf( "Elapsed : %ld\n", elapsed );

ts_last.tv_nsec += period_milli * 1000000L;
if( ts_last.tv_nsec >= 1000000000L )
{
ts_last.tv_nsec -= 1000000000L;
ts_last.tv_sec++;
}
}
}
return 0;
}

每次所需时间段过去时,“先前”时间都会更新为使用该时间段过去的预期时间,而不是实际时间。此示例在每次轮询之间使用 1 毫秒的 sleep 时间,这可能超出了顶部。

关于Clock_Gettime() 抖动?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30700849/

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