gpt4 book ai didi

c++ - linux 使用 clock_nanosleep 休眠

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

我想使用 clock_nanosleep 等待 1 微秒。据我所知,我必须给出一个绝对时间作为输入。在这种情况下,以下代码可以吗?

deadline.tv_sec = 0;
deadline.tv_nsec = 1000;

clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &deadline, NULL);

最佳答案

您的 deadline tv 不是绝对时间。要形成绝对时间,请使用 clock_gettime() ( http://linux.die.net/man/3/clock_gettime ) 获取当前时间,然后添加您的 sleep 间隔。

struct timespec deadline;
clock_gettime(CLOCK_MONOTONIC, &deadline);

// Add the time you want to sleep
deadline.tv_nsec += 1000;

// Normalize the time to account for the second boundary
if(deadline.tv_nsec >= 1000000000) {
deadline.tv_nsec -= 1000000000;
deadline.tv_sec++;
}
clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &deadline, NULL);

请注意,我使用的是 CLOCK_MONOTONIC 而不是 CLOCK_REALTIME。您实际上并不关心现在几点,您只希望时钟保持一致。

关于c++ - linux 使用 clock_nanosleep 休眠,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20332382/

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