开发者

How to use nanosleep for sleeping random amounts of time?

Im trying to use the function nanosleep to make my process sleep for a random amount of time between 1/10th of a second?

im using srand() to seed my random number generator, with the process id, that is, im calling:

srand(getpid());

then using

struct timespec delay;
delay.tv_sec = 0;
delay.tv_nsec = rand();
nanosleep(&delay, NULL);

How can i make sure im s开发者_JS百科leeping for 0..1/10th of a second?


I'd say you just need 100000000ULL * rand() / RAND_MAX nanoseconds, this is at most 0.1s and at least 0s. Alternatively, try usleep() with argument 100000ULL * rand() / RAND_MAX. (I think usleep requires fewer CPU resources.)

(Edit: Added "unsigned long long" literal specifier to ensure that the number fits. See comments below, and thanks to caf for pointing this out!)


you need to "cap" your rand(), like:

delay.tv_nsec = rand() % 1e8;

Some experts say that this is not the optimal way to do it, because you use the LSB of the number and they are not as "random" as the higher bits, but this is fast and reliable.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜