PlayHardGoPro PlayHardGoPro - 6 months ago 13
Linux Question

How to sleep a process for a vary interval of miliseconds

I'm reading about

Sleep
nanosleep
usleep
but I'm not sure which one to use nor how to use it exactly...

I need to make a process sleep for a
random
number each '10, 20, 30, 40, 50 miliseconds'.

How may I achieve that ?

I'm testing like so:

Sleep(rand()%1500);


But I'd like to know if it's possible to set that interval in a single line.

Answer
  1. You've to reference the unistd.h.
  2. Then use the functions rand() & usleep().

A sample may be:

// edited as @JonathanLeffler advised
...
#include <unistd.h>
...

void foo(int someArgs) {
    ...
    useconds_t sleepTime;

    ...
    // create random int r where 0 <= r < 0x7fffffff
    sleepTime = (useconds_t)(((rand() % 5) + 1) * 10000); 
    usleep(sleepTime);
    ...

    // for a single line preference, following may work it out
    usleep(((rand() % 5) + 1) * 10000);

}
Comments