0
閱讀文檔:https://docs.python.org/2/library/multiprocessing.html 我決定編寫一個cpu密集型代碼,並將多處理與串行計算進行比較。 首先,如果這個庫使用多處理,那麼爲什麼我只看到1個python.exe進程? 其次,爲什麼串行計算需要12秒,而多處理需要22秒?python多處理沒有使用多核心
串行代碼:
from datetime import datetime
def calc_fib(ind):
fb = 1
if ind >= 3:
prev = 1
i = 2
while i < ind:
prev_tmp = fb
fb += prev
prev = prev_tmp
i += 1
return fb
def long_calc_fib(ind):
val = 0
for j in range(500):
val = calc_fib(ind)
return val
if __name__ == "__main__":
t1 = datetime.now()
for i in range(10):
tmp = long_calc_fib(10000)
t2 = datetime.now()
print str(t2 - t1)
多池代碼:
from datetime import datetime
from multiprocessing.pool import ThreadPool
def calc_fib(ind):
fb = 1
if ind >= 3:
prev = 1
i = 2
while i < ind:
prev_tmp = fb
fb += prev
prev = prev_tmp
i += 1
return fb
def long_calc_fib(ind):
val = 0
for j in range(500):
val = calc_fib(ind)
return val
if __name__ == "__main__":
t1 = datetime.now()
pool = ThreadPool(processes=10)
async_results = []
for i in range(10):
async_results.append(pool.apply_async(long_calc_fib, (10000,)))
for res in async_results:
tmp = res.get()
t2 = datetime.now()
print str(t2 - t1)
這是因爲一個線程只是一個進程的子任務 - 如果你想利用多個CPU核心,你需要額外的進程。 – ACimander