Time taken for sequential code(seq.py
),
import time
def countDown(n):
while n > 0:
n -= 1
n = 50000000
start = time.time()
countDown(n)
end = time.time()
print(end-start)
is,
$ python3.6 seq.py
4.209718227386475
$ python3.6 seq.py
4.007786750793457
$ python3.6 seq.py
4.0265843868255615
$
Time taken for threaded version(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)
is,
$ 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 interpreter should not allow CPU bound threads to release GIL.
Expecting usingThreads.py
to take more execution time than seq.py
, because,
1) Any one thread is executing at a time, despite 4 cores
2) Time taken for failed attempts to acquire GIL from thread1 by thread2(and vice versa) should add delay in execution.
Edit:
With 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
Question:
Why usingThread.py
performs better than seq.py
?