I am learning how to run simple function on multiple threads in Python.
Assume this simple code:
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") This is how I try to run the foo() function on multiple threads:
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") But the run time is the same, what is the problem here, please? Thanks a lot