如何才能让睡眠时间小于0.001s/1ms?
如果我使用这个,它会显示它只休眠 1 毫秒。可以少睡一点吗?
$ time sleep 0.00001
sleep 0.00001 0,00s user 0,00s system 79% cpu 0,002 total
答案1
sleep
通常使用nanosleep(2)
系统调用。但是,尽管这个系统调用具有高精度参数,但实际精度将取决于 Linux 使用的计时器。
通常,Linux 内核是使用该CONFIG_HZ=250
选项编译的。 (看/boot/config-...
)。
扩展CONFIG_HIGH_RES_TIMERS
可以提高准确性。看https://elinux.org/High_Resolution_Timers
那里有一个旧的行为,忙等待,但在现在的内核中没有:
In order to support applications requiring much more precise pauses (e.g., in order to control some time-critical hardware), nanosleep() would handle pauses of up to 2 milliseconds by busy waiting with mi‐ crosecond precision when called from a thread scheduled under a real- time policy like SCHED_FIFO or SCHED_RR. This special extension was removed in kernel 2.5.39, and is thus not available in Linux 2.6.0 and later kernels.
另请注意,分叉进程并加载sleep
程序需要一些时间。在我的系统上,我有:
time sleep 0.000
real 0m0,007s
user 0m0,001s
sys 0m0,006s