我正在学习如何在 Python 中的多线程上运行简单的函数。
假设这个简单的代码:
from itertools import product
all_combinations = []
for cas in range(3):
target_sum = 10
combinations = product(range(target_sum + 1), repeat=4)
valid_combinations = [combo for combo in combinations if sum(combo) == target_sum]
all_combinations.append(valid_combinations)
compute_combo = []
for a in all_combinations[2]:
for b in all_combinations[1]:
for c in all_combinations[0]:
compute_combo.append([a, b, c])
def foo(bar):
max_combo = 0
for j in bar:
for a in j:
suma = a[0] + a[1] + 3*a[2] + a[3]
if suma > max_combo:
max_combo = suma
return max_combo
import time
start_time_simple = time.time()
result_simple = foo(compute_combo)
print(f"1 CPU result: {result_simple}")
end_time_simple = time.time()
execution_time_simple = end_time_simple - start_time_simple
print(f"1 CPU run time: {execution_time_simple} s")
这就是我尝试在多个线程上运行 foo() 函数的方法:
from multiprocessing.dummy import Pool as ThreadPool
start_time_par = time.time()
pool = ThreadPool(4)
result_par = pool.map(foo, [compute_combo])
pool.close()
pool.join()
end_time_par = time.time()
execution_time_par = end_time_par - start_time_par
print(f"4 CPUs result {result_par}")
print(f"4 CPUs run time: {execution_time_par} s")
但是运行时间是一样的,请问这里有什么问题吗?非常感谢
改用线程:
def func1:
while True: