How to use nanosleep for sleeping random amounts of time?

烈酒焚心 提交于 2019-12-02 05:55:28

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.

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