时间采取的顺序代码(seq.py
)为什么GIL不允许执行线程代码?
import time
def countDown(n):
while n > 0:
n -= 1
n = 50000000
start = time.time()
countDown(n)
end = time.time()
print(end-start)
是,
$ python3.6 seq.py
4.209718227386475
$ python3.6 seq.py
4.007786750793457
$ python3.6 seq.py
4.0265843868255615
$
采取螺纹版本(usingThreads.py
)时间,
from threading import Thread
import time
def countDown(n):
while n > 0:
n -= 1
n = 50000000
t1 = Thread(target=countDown, args=(n//2,))
t1.daemon = True
t2 = Thread(target=countDown, args=(n//2,))
t2.daemon = True
start = time.time()
t1.start()
t2.start()
t1.join()
t2.join()
end = time.time()
print(end-start)
是,
$ python3.6 usingThreads.py
4.1083903312683105
$ python3.6 usingThreads.py
4.093154668807983
$ python3.6 usingThreads.py
4.092989921569824
$ python3.6 usingThreads.py
4.116031885147095
$
$ nproc
4
$
Python解释器不应该允许CPU绑定线程释放GIL。
期待usingThreads.py
采取更多的执行时间比seq.py
,因为,
1)任何一个线程在时间执行,尽管4个内核
2)取为失败的尝试时间从线程1获取GIL通过thread2(反之亦然)应该延迟执行。
编辑:
随着n=500000000
$ python3.6 seq.py
40.22602105140686
$ python3.6 seq.py
40.510098457336426
$ python3.6 seq.py
40.04688620567322
$
$ python3.6 usingThreads.py
40.91394829750061
$ python3.6 usingThreads.py
42.30081081390381
$ python3.6 usingThreads.py
41.328694581985474
问:
为什么比seq.py
更好usingThread.py
执行?
在我看来就像使用线程通常是越慢,seq.py次仅快于一个。 – barny
我怀疑这是因为你在线程版本中使用了'join()',这可能消除了通常与使用线程相关的大部分开销。 – martineau
@martineau这是我知道等待线程完成的唯一途径,然后计算完成工作所需的时间。如何避免'join()'? – overexchange