我试图处理一个函数20次,并且试图使用多线程来减少耗时,但是串行处理的实际执行时间比mutithread处理要快得多,我有点困惑关于python中的多线程,在我看来,它会使程序更快吗?还是应该使用多处理或池?
start = time.time()
N = 100
M = 100
NumOfThread = 20
threads = []
start = time.time()
for i in range(NumOfThread):
t = threading.Thread(target = mccala,args=(N,M))
t.start()
threads.append(t)
for thread in threads:
thread.join()
end = time.time()
print(end - start )
这将返回4秒,但是像这样的串行处理
start = time.time()
for i in range(NumOfThread):
t = mccala(N,M)
end = time.time()
print(end- start)
让我返回1秒
mccala函数如下所示
def mccala (searchRange,density):
selectedCore = [0]*(searchRange*density)
i = random.randint(0,searchRange*density)
core = i/ (searchRange*density)
selectedCore[i] = 1
k =0
while k < K :
lam = random.uniform(core-1/searchRange,core+1/searchRange)
if lam > 0 and lam < 1:
response = rm.binomial(1,func(lam),1)[0]
if response == 1:
if lam < core :
core = core - 1/ (searchRange*density)
i -=1
else:
core = core + 1/(searchRange*density)
i+= 1
selectedCore[i] += 1
k += 1
return q.put([i/K*10 for i in selectedCore])
导入包是
import math
import numpy.random as rm
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
import random
import threading
import queue,time
from multiprocessing import Pool