我想使用clock_nanosleep等待1微秒.据我了解,我必须给出绝对时间作为输入.在这种情况下,以下代码是否可以?
deadline.tv_sec = 0;
deadline.tv_nsec = 1000;
clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &deadline, NULL);
Run Code Online (Sandbox Code Playgroud)
Pet*_*ter 21
你的截止日期电视不是一个绝对的时间.要形成绝对时间,请使用clock_gettime()(http://linux.die.net/man/3/clock_gettime)获取当前时间 ,然后添加睡眠间隔.
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);
Run Code Online (Sandbox Code Playgroud)
请注意,我使用CLOCK_MONOTONIC而不是CLOCK_REALTIME.你实际上并不关心它是什么时候,你只是想让时钟保持一致.
据我了解,我必须给出一个绝对时间作为输入。
不,该flags参数允许您选择相对时间或绝对时间。你要
clock_nanosleep(CLOCK_REALTIME, 0, &deadline, NULL);
Run Code Online (Sandbox Code Playgroud)
从现在开始指定一微秒。