C ++中usleep(0)对Linux的影响

时间:2012-10-10 15:58:35

标签: c++ linux usleep

调用usleep(0)的{​​{3}}状态无效。但是,在我的系统(RHEL 5.2)上运行下面的C ++代码的小片段时,我发现它实际上看起来与usleep(1)具有相同的效果。这是预期的,如果是这样,为什么文档和我在现实生活中看到的差异呢?

展览A

代码:

#include <unistd.h>

int main()
{
    for( int i = 0; i < 10000; i++ )
    {
        usleep(1);
    }
}

输出:

$ time ./test
real   0m10.124s
user   0m0.001s
sys    0m0.000s

图表B

代码:

#include <unistd.h>

int main()
{
    for( int i = 0; i < 10000; i++ )
    {
        usleep(1);
        usleep(0);
    }
}

输出:

$ time ./test
real   0m20.770s
user   0m0.002s
sys    0m0.001s

6 个答案:

答案 0 :(得分:13)

技术上它应该没有效果。但是你必须记住,传递的值用作最小值,而不是绝对值,因此系统可以自由地使用尽可能小的间隔。

答案 1 :(得分:4)

我只想指出这里使用的时间命令。如果要检查程序内存,CPU,时间统计,则应使用/usr/bin/time而不是time命令。当您在没有完整路径的情况下调用时间时,将调用内置时间命令。看看差异。

没有完整路径:

# time -v ./a.out
-bash: -v: command not found

real    0m0.001s
user    0m0.000s
sys     0m0.001s

完整路径:

# /usr/bin/time -v ./a.out
Command being timed: "./a.out"
User time (seconds): 0.00
System time (seconds): 0.00
Percent of CPU this job got: 0%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:10.87
Average shared text size (kbytes): 0
Average unshared data size (kbytes): 0
Average stack size (kbytes): 0
Average total size (kbytes): 0
Maximum resident set size (kbytes): 0
Average resident set size (kbytes): 0
Major (requiring I/O) page faults: 0
Minor (reclaiming a frame) page faults: 220
Voluntary context switches: 10001
Involuntary context switches: 1
Swaps: 0
File system inputs: 0
File system outputs: 0
Socket messages sent: 0
Socket messages received: 0
Signals delivered: 0
Page size (bytes): 4096
Exit status: 0

man time用于/usr/bin/time手册,并使用help time获取内置时间信息。

答案 2 :(得分:3)

我必须查看源代码以确保,但我的猜测是它不是“没有效果”,但它可能仍然小于usleep(1) - 仍然存在函数调用开销,这可能是在紧密循环中可测量,即使库调用只是检查其参数并立即返回,也避免了更常见的设置定时器/回调并调用调度程序的过程。

答案 3 :(得分:2)

该文档从1997年开始,不确定它是否适用于当前的RHEL5,我的redhat dev系统手册页为usleep并不表示0的睡眠时间没有效果。

您传递的参数是睡眠的最短时间。无法保证线程将在指定的时间后唤醒。考虑到调度程序的特定动态,可能会导致延迟时间长于预期。

答案 4 :(得分:2)

usleep()sleep()已转换为nanosleep()系统调用。试试strace您的计划,您就会看到它。来自nanosleep() manual

   nanosleep() suspends the execution of the calling thread until either
   at least the time specified in *req has elapsed, or the delivery of a
   signal that triggers the invocation of a handler in the calling
   thread or that terminates the process.

所以我认为ulseep(0)会产生一个中断和一个上下文切换。

答案 5 :(得分:0)

根据我的经验,它有一个效果:它正在调用中断 在多线程编程中,最好在最短的时间内释放处理器。