def dowork():
y = []
z = []
ab = 0
start_time = time.time()
t = threading.current_thread()
for x in range(0,1500):
y.append(random.randint(0,100000))
for x in range(0,1500):
z.append(random.randint(0,1000))
for x in range(0,100):
for k in range(0,len(z)):
ab += y[k] ** z[k]
print(" %.50s..." % ab)
print("--- %.6s seconds --- %s" % (time.time() - start_time, t.name))
#do the work!
threads = []
for x in range(0,4): #4 threads
threads.append(threading.Thread(target=dowork))
for x in threads:
x.start() # and they are off
結果:多線程VS單線程計算
23949968699026357507152486869104218631097704347109...
--- 11.899 seconds --- Thread-2
10632599432628604090664113776561125984322566079319...
--- 11.924 seconds --- Thread-4
20488842520966388603734530904324501550532057464424...
--- 12.073 seconds --- Thread-1
17247910051860808132548857670360685101748752056479...
--- 12.115 seconds --- Thread-3
[Finished in 12.2s]
現在讓我們做吧在1線:
def dowork():
y = []
z = []
ab = 0
start_time = time.time()
t = threading.current_thread()
for x in range(0,1500):
y.append(random.randint(0,100000))
for x in range(0,1500):
z.append(random.randint(0,1000))
for x in range(0,100):
for k in range(0,len(z)):
ab += y[k] ** z[k]
print(" %.50s..." % ab)
print("--- %.6s seconds --- %s" % (time.time() - start_time, t.name))
# print(threadtest())
threads = []
for x in range(0,4):
threads.append(True)
for x in threads:
dowork()
結果:
14283744921265630410246013584722456869128720814937...
--- 2.8463 seconds --- MainThread
13487957813644386002497605118558198407322675045349...
--- 2.7690 seconds --- MainThread
15058500261169362071147461573764693796710045625582...
--- 2.7372 seconds --- MainThread
77481355564746169357229771752308217188584725215300...
--- 2.7168 seconds --- MainThread
[Finished in 11.1s]
爲什麼單線程和多線程腳本有相同處理時間? 不應該多線程實現只有1 /#線程少? (我知道當你達到你的最大CPU線程有收益遞減)
我搞砸了我的實施?
的線程不會因CPython的的_Global解釋Lock_的並行運行。這是CPython的一個衆所周知的缺陷。嘗試多處理。 –
好的,如果你給我一個鏈接,或者多處理,請給我一個答案,我會接受它。你已經回答了。 – c3cris
https://docs.python.org/2/library/multiprocessing.html –