问题描述
我试着去使用此功能了nanosleep使我的睡眠过程中的时间1/10之间的第二随机量?
Im trying to use the function nanosleep to make my process sleep for a random amount of time between 1/10th of a second?
使用srand()函数种子我的随机数发生器,与进程ID IM,即,即时通讯主叫
im using srand() to seed my random number generator, with the process id, that is, im calling:
srand(getpid());
然后用
struct timespec delay;
delay.tv_sec = 0;
delay.tv_nsec = rand();
nanosleep(&delay, NULL);
我怎样才能确保IM睡了一秒钟的0..1 / 10?
How can i make sure im sleeping for 0..1/10th of a second?
推荐答案
我说,你只需要 100000000ULL * RAND()/ RAND_MAX
纳秒,这是最多0.1秒至少0。或者,尝试 usleep()函式
与参数 100000ULL * RAND()/ RAND_MAX
。 (我认为 usleep
需要更少的CPU资源。)
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.)
(编辑:的补充无符号加长的文字说明,以确保符合数见下面的意见,并感谢CAF指出这点)
( Added "unsigned long long" literal specifier to ensure that the number fits. See comments below, and thanks to caf for pointing this out!)
这篇关于如何使用了nanosleep昏睡随机大量的时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!