如何多线程(多进程)加速while循环(语言-python)?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何多线程(多进程)加速while循环(语言-python)?相关的知识,希望对你有一定的参考价值。
import numpy as np
import os
import sys
import multiprocess as mp
import time
def MCS(input_data, med):
t1 = time.perf_counter()
left = 0
lp = 0
while True:
lp = lp + 1
data_pool = input_data + left
output_data = med * 0.05 * data_pool / (10000 + med)
output_data = np.where(output_data > data_pool, data_pool, output_data)
left = data_pool - output_data
cri = (input_data - output_data) / input_data * 100
print(lp, data_pool, output_data, cri)
if cri <= 1:
break
t2 = time.perf_counter()
print(f'Finished in t2 - t1 seconds')
if name == 'main':
pool = mp.Pool(processes=10)
pool.apply_async(MCS, args=(100, 0.4))
pool.close()
pool.join()
#运行结果和没有使用多线程的结果相差不大。希望可以利用多线程显著提高while循环的速度,节省时间。
import os
import sys
import multiprocessing as mp
import time
def MCS(input_data, med):
#t1 = time.perf_counter()
left = 0
lp = 0
while True:
lp = lp + 1
data_pool = input_data + left
output_data = med * 0.05 * data_pool / (10000 + med)
output_data = np.where(output_data > data_pool, data_pool, output_data)
left = data_pool - output_data
cri = (input_data - output_data) / input_data * 100
#print(lp, data_pool, output_data, cri)
if cri <= 1:
break
t2 = time.perf_counter()
#print(f'Finished in t2 - t1 seconds')
if __name__ == "__main__":
pool = mp.Pool(processes=5)
tasks = []
for i in np.linspace(0.4, 0.6, num = 10):
tasks.append([100, i])
t1 = time.perf_counter()
pool.starmap(MCS, tasks)
#pool.apply_async(MCS, args=(100, 0.4))
t2 = time.perf_counter()
#pool.join()
#pool.close()
for i in np.linspace(0.4, 0.6, num = 10):
MCS(100, i)
t3 = time.perf_counter()
print(f'Finished in t2 - t1 seconds')
print(f'Finished in t3 - t2 seconds')
原因可能是只运行了一个例子,
如图测试了10个例子,测试结果如下
Finished in 15.062450630997773 seconds
Finished in 73.1936681799998 seconds
并行确实有一定的加速。本回答被提问者采纳
以上是关于如何多线程(多进程)加速while循环(语言-python)?的主要内容,如果未能解决你的问题,请参考以下文章