How to use nanosleep for sleeping random amounts of time?

China☆狼群 提交于 2019-12-02 08:25:30

问题


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 sleeping for 0..1/10th of a second?


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/6405850/how-to-use-nanosleep-for-sleeping-random-amounts-of-time

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!