[英]get the list and input from one function and run them in different function
[英]Run one function on different CPUs
我有一台機器有兩個 CPU,每個 CPU 有不同數量的內核。 我的 python 代碼中有一個 function。 如何在每個 CPU 上運行此 function?
在這種情況下,我需要運行兩次 function 因為我有兩個 CPU。
我想要這個是因為我想比較不同 CPU 的性能。 這可以是代碼的一部分。 如果代碼沒有以正確的方式編寫,請告訴我。
import multiprocessing
def my_function():
print ("This Function needs high computation")
# Add code of function
pool = multiprocessing.Pool()
jobs = []
for j in range(2): #how can I run function depends on the number of CPUs?
p = multiprocessing.Process(target = my_function)
jobs.append(p)
p.start()
我已經閱讀了很多帖子,但沒有找到適合我的問題的答案。
concurrent
package 以最佳方式處理資源分配,因此您不必指定任何特定的進程/線程 ID,無論如何都是特定於操作系統的。
如果您想使用多個進程或多個線程運行 function,您可以使用 class 為您完成它:
from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
from typing import Generator
class ConcurrentExecutor:
@staticmethod
def _concurrent_execution(executor, func, values):
with executor() as ex:
if isinstance(values, Generator):
return list(ex.map(lambda args: func(*args), values))
return list(ex.map(func, values))
@staticmethod
def concurrent_process_execution(func, values):
return ConcurrentExecutor._concurrent_execution(
ProcessPoolExecutor, func, values, verbose
)
@staticmethod
def concurrent_thread_execution(func, values):
return ConcurrentExecutor._concurrent_execution(
ThreadPoolExecutor, func, values, verbose
)
然后你可以用它執行任何 function,即使是 arguments。 如果它是單個參數函數:
from concurrency import ConcurrentExecutor as concex
# Single argument function that prints the input
def single_arg_func(arg):
print(arg)
# Dummy list of 5 different input values
n_values = 5
arg_values = [x for x in range(n_values)]
# We want to run the function concurrently for each value in values
concex.concurrent_thread_execution(single_arg_func, arg_values)
或使用多個 arguments:
from concurrency import ConcurrentExecutor as concex
# Multi argument function that prints the input
def multi_arg_func(arg1, arg2):
print(arg1, arg2)
# Dummy list of 5 different input values per argument
n_values = 5
arg1_values = [x for x in range(n_values)]
arg2_values = [2*x for x in range(n_values)]
# Create a generator of combinations of values for the 2 arguments
args_values = ((arg1_values[i], arg2_values[i]) for i in range(n_values))
# We want to run the function concurrently for each value combination
concex.concurrent_thread_execution(multi_arg_func, args_values)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.