我在python中编写了以下代码,以便处理多线程并允许并行运行各种方法。至少这是我所希望的
import threading
import time
class FuncThread(threading.Thread):
results = None
def __init__(self, target, *args):
threading.Thread.__init__(self)
self._target = target
self._args = args
def run(self):
assert( self._target!= None )
self.results = self._target(*self._args[0])
def run_all(func):
threads = []
for i in range(len(func)):
f = func[i]
param = f[1:]
f = f[0]
if param != None:
t = FuncThread(f, param)
else:
t = FuncThread(f)
t.start()
threads.append(t)
# Wait for all threads to complete
#print ('********** waiting for threads to complete')
results = []
for t in threads:
t.join()
for t in threads:
results.append(t.results)
#print ('Finished: ' + str(t.results))
#print ('********** threads are done')
return results
我写了以下测试以测量时间但是我没有看到任何改进次数!
if __name__ == '__main__':
def func1(data, key):
#print ("data={0}; key={1}".format(str(data), str(key)))
c = 0
for i in range(50000):
c += data
return c
def func2(data, key):
#print ("data={0}; key={1}".format(str(data), str(key)))
c = 1
m = 1
for i in range(50000):
m *= c
c += 1
#print(c, key)
return c,m
print('\nregular call:\n')
base = time.time()
for i in range(10):
func1(34, 2)
func2(3, 2)
print('spent: ' + str(time.time() - base) + ' seconds')
print('\nnow let\'s try with threads:\n')
base = time.time()
for i in range(10):
run_all([ (func1, 34, 2) , [func2, 3, 2] ] )
print('spent: ' + str(time.time() - base) + ' seconds')
使用多线程时,结果没有显示任何时间的改善,相反,它显示出一些回归和缓慢
regular call:
spent: 12.752724409103394 seconds
now let's try with threads:
spent: 13.019697904586792 seconds
我做错了什么?