有一個愉快的一天!並聯無功能是可能的嗎?
我有兩個功能。首先沒有並聯:
def non_parallel():
for a in range(500):
for b in range(500):
for c in range(500):
try:
if (1+1/a)*(1+1/b)*(1+1/c)==3:
print("a=",a,", b=",b,", c=", c, sep='')
except ZeroDivisionError:
pass
print ("Run time: ", datetime.now() - startTime)
二是並聯:
def parallel(a):
for b in range(500):
for c in range(500):
try:
if (1+1/a)*(1+1/b)*(1+1/c)==3:
print("a=",a,", b=",b,", c=", c, sep='')
except ZeroDivisionError:
pass
呼叫並聯功能(我有2個內核):
Parallel(n_jobs=num_cores)(delayed(parallel)(a) for a in range(500))
但是,如果沒有並聯我的腳本運行0:02:03.972283 並聯功能:02:45.182950
我認爲,並聯函數運行時間更長,因爲函數調用需要更多時間。這是真的?是否可以並行其他方式?
全碼:
#!/usr/bin/python3
from datetime import datetime
from joblib import Parallel, delayed
import multiprocessing
num_cores = multiprocessing.cpu_count()
print (num_cores)
startTime = datetime.now()
def non_parallel():
for a in range(500):
for b in range(500):
for c in range(500):
try:
if (1+1/a)*(1+1/b)*(1+1/c)==3:
print("a=",a,", b=",b,", c=", c, sep='')
except ZeroDivisionError:
pass
print ("Time: ", datetime.now() - startTime)
startTime = datetime.now()
def parallel(a):
for b in range(500):
for c in range(500):
try:
if (1+1/a)*(1+1/b)*(1+1/c)==3:
print("a=",a,", b=",b,", c=", c, sep='')
except ZeroDivisionError:
pass
non_parallel()
Parallel(n_jobs=num_cores)(delayed(parallel)(a) for a in range(500))
print ("Time: ", datetime.now() - startTime)
print ("End")