我在使用python 2.7多線程和使用隊列時遇到問題。我希望線程的代碼只需要一個線程的一半,但我認爲我做錯了什麼。我正在使用斐波那契序列的簡單循環技術來最好地顯示問題。Python在多線程時節省執行時間
這是沒有線程和隊列的代碼。它的執行時間爲19.9190001488秒。
import time
start_time = time.time()
def fibonacci(priority, num):
if num == 1 or num == 2:
return 1
a = 1
b = 1
for i in range(num-2):
c = a + b
b = a
a = c
return c
print fibonacci(0, 200000)
print fibonacci(1, 100)
print fibonacci(2, 200000)
print fibonacci(3, 2)
print("%s seconds" % (time.time() - start_time))
這裏是線程和隊列的代碼。它的執行時間爲21.7269999981秒。
import time
start_time = time.time()
from Queue import *
from threading import *
numbers = [200000,100,200000,2]
q = PriorityQueue()
threads = []
def fibonacci(priority, num):
if num == 1 or num == 2:
q.put((priority, 1))
return
a = 1
b = 1
for i in range(num-2):
c = a + b
b = a
a = c
q.put((priority, c))
return
for i in range(4):
priority = i
num = numbers[i]
t = Thread(target = fibonacci, args = (priority, num))
threads.append(t)
#print threads
for t in threads:
t.start()
for t in threads:
t.join()
while not q.empty():
ans = q.get()
q.task_done()
print ans[1]
print("%s seconds" % (time.time() - start_time))
我認爲會發生的事情是多線程代碼佔用無線程代碼的一半長。本質上,我認爲所有線程同時工作,所以計算200,000斐波那契數的2個線程將同時完成,所以執行速度是沒有線程的代碼的兩倍。顯然這不是發生了什麼事。難道我做錯了什麼?我只是想同時執行所有線程,按照它們開始的順序進行打印,而花費最長時間的線程幾乎是執行時間。
編輯:
我更新了我的代碼中使用的過程,但現在不被打印結果。只顯示0.163000106812秒的執行時間。下面是新的代碼:
import time
start_time = time.time()
from Queue import *
from multiprocessing import *
numbers = [200000,100,200000,2]
q = PriorityQueue()
processes = []
def fibonacci(priority, num):
if num == 1 or num == 2:
q.put((priority, 1))
return
a = 1
b = 1
for i in range(num-2):
c = a + b
b = a
a = c
q.put((priority, c))
return
for i in range(4):
priority = i
num = numbers[i]
p = Process(target = fibonacci, args = (priority, num))
processes.append(p)
#print processes
for p in processes:
p.start()
for p in processes:
p.join()
while not q.empty():
ans = q.get()
q.task_done()
print ans[1]
print("%s seconds" % (time.time() - start_time))
你正在使用哪個操作系統?視窗? – Dunes
是的窗口8.1 –