linux sleeping with clock_nanosleep

16,901

Solution 1

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.

Solution 2

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.

Solution 3

@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.

Share:
16,901

Related videos on Youtube

Avb Avb
Author by

Avb Avb

Updated on July 12, 2022

Comments

  • Avb Avb
    Avb Avb almost 2 years

    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);
    
    • PlasmaHH
      PlasmaHH over 10 years
      what does the manpage say, and when you tried it, what did you observe?
    • PlasmaHH
      PlasmaHH over 10 years
      I am pretty sure that here more than a microsecond has passed since the epoch, but since you haven't mentioned why it seems that something is wrong with your implementation, it might be different at your location.
    • Mike Seymour
      Mike Seymour over 10 years
      @AvbAvb: You can use TIMER_ABSTIME to set absolute time, or 0 to set relative time. It looks like you want to do the latter.
  • ryanyuyu
    ryanyuyu over 9 years
    Can you elaborate on this some more? Maybe provide example code?