Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

linux sleeping with clock_nanosleep

Tags:

c++

sleep

clock

I want to use clock_nanosleep for waiting of 1 microsec.. As far as I understand, I have to give an absolute time as input. Is the following code okay in this case?

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

clock_nanosleep(CLOCK_REALTIME, TIMER_ABSTIME, &deadline, NULL);
like image 488
Avb Avb Avatar asked Dec 02 '13 15:12

Avb Avb


4 Answers

Your deadline tv is not an absolute time. To form an absolute time, get the current time with clock_gettime() (http://linux.die.net/man/3/clock_gettime), then add your sleep interval.

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

Note that I'm using CLOCK_MONOTONIC instead of CLOCK_REALTIME. You don't actually care what time it is, you just want the clock to be consistent.

like image 110
Peter Avatar answered Nov 03 '22 02:11

Peter


As far as I understand, I have to give an absolute time as input.

No, the flags argument allows you to choose relative or absolute time. You want

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

to specify one microsecond from now.

like image 36
Mike Seymour Avatar answered Nov 03 '22 01:11

Mike Seymour


@ryanyuyu

sample code::

void mysleep_ms(int milisec)
{
    struct timespec res;
    res.tv_sec = milisec/1000;
    res.tv_nsec = (milisec*1000000) % 1000000000;
    clock_nanosleep(CLOCK_MONOTONIC, 0, &res, NULL);
}

this is monotonic clock based sleep function. please refer it.

like image 4
cpplover - Slw Essencial Avatar answered Nov 03 '22 02:11

cpplover - Slw Essencial


The most precise way to pause a program for a single microsecond (1us) is busy-waiting, sleep mechanism (nanosleep or clock_nanosleep) will involve task scheduling and context switch, whose latencies are greater than 1us.

Reference:

delays - Information on the various kernel delay / sleep mechanisms

like image 1
foool Avatar answered Nov 03 '22 01:11

foool