11

usleep的文档指出调用usleep(0)无效。但是,在我的系统(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
4

7 回答 7

15

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

于 2012-10-10T16:08:26.100 回答
5

我只是想指出这里使用的时间命令。如果你想检查你的程序内存、CPU、时间统计,你应该使用/usr/bin/time而不是只使用命令。time当您在没有完整路径的情况下调用 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/timehelp time

于 2013-11-26T08:32:19.273 回答
3

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

于 2012-10-10T16:08:17.487 回答
3

usleep()并被sleep()翻译成nanosleep()系统调用。试试strace你的程序,你会看到的。从nanosleep() 手册

   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) 会产生中断和上下文切换。

于 2015-02-09T22:03:00.317 回答
2

该文档是 1997 年的,不确定它是否适用于当前的 RHEL5,我的 Redhat dev systems man page for usleep 并未表明睡眠时间为 0 无效。

您传递的参数是睡眠的最短时间。不能保证线程会在指定的时间后唤醒。鉴于调度程序的特定动态,它可能会导致比预期更长的延迟。

于 2012-10-10T16:08:01.703 回答
1

它还取决于 udelay 是否在短时间内实现为繁忙循环。

于 2012-10-10T20:53:31.980 回答
0

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

于 2015-01-08T01:51:46.887 回答