哪个更好?
time.sleep(delayTime)
还是
select.select([],[],[],delayTime)
它们是否等效?
select 更有效吗?
哪个更好?
time.sleep(delayTime)
还是
select.select([],[],[],delayTime)
它们是否等效?
select 更有效吗?
使用timeit
函数在Python中编写测试非常简单,但我喜欢使用IPython进行快速测试(http://ipython.org/)。以下是我的测试结果:
$ ipython
import time,select
%timeit time.sleep(0)
1000000 loops, best of 3: 655 ns per loop
%timeit select.select([],[],[],0)
1000000 loops, best of 3: 902 ns per loop
但如果你没有访问ipython的权限,而更喜欢使用本地命令行中的timeit
:
$ python -m timeit -s "import time,select" "time.sleep(0)"
1000000 loops, best of 3: 0.583 usec per loop
$ python -m timeit -s "import time,select" "select.select([],[],[],0)"
1000000 loops, best of 3: 0.777 usec per loop
time.sleep(delayTime)
select.select([],[],[],delayTime)
这是 Unix select() 系统调用的直接接口。前三个参数是“可等待对象”的序列:
现在,我们了解了这两个接口,就能理解答案取决于目的:
如果你只想暂停当前线程-第一种方法更简单。但是如果有需要等待的对象-请使用第二种方法。
在效率方面-我认为如果你只是寻找最简单的用例(只暂停主线程),则没有区别。
你如何定义效率?在大多数情况下,使用睡眠和选择来观察是否有空间/缓冲区。如果空间不可用,则可以选择等待并观察缓冲区何时为空,然后执行我们的操作。 sleep() 内部使用 select()。因此,我认为取决于你更喜欢哪个方法。