Created
December 20, 2018 14:20
-
-
Save staticor/d7e1c399a075d07c9b1ce4390ef97a14 to your computer and use it in GitHub Desktop.
GIL is not efficient as you wish.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import threading | |
from multiprocessing import Queue | |
import copy | |
import time | |
def job(l, q): | |
res = sum(l) | |
q.put(res) | |
def multithreading(l): | |
q = Queue() | |
threads = [] | |
for i in range(4): | |
t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i) | |
t.start() | |
threads.append(t) | |
[t.join() for t in threads] | |
total = 0 | |
for _ in range(4): | |
total += q.get() | |
print(total) | |
def normal(l): | |
total = sum(l) | |
print(total) | |
if __name__ == '__main__': | |
l = list(range(1000000)) | |
s_t = time.time() | |
normal(l*4) | |
print('normal: ',time.time()-s_t) | |
s_t = time.time() | |
multithreading(l) | |
print('multithreading: ', time.time()-s_t) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment