当前,我在循环中的一个循环中运行一个循环,然后传递一个已安装类的一组新参数,然后首先调用class.reset((函数,然后调用class.main((函数。
由于class.run非常占用cpu,我确实想多处理它,但我还没有找到如何做到这一点的例子。
以下是需要多处理的代码:
st = Strategy() /// Strategy is my class
for start_delay in range(0, PAR_BT_CYCLE_LENGTH_END, 1):
for cycle_length in range(PAR_BT_CYCLE_LENGTH_START, PAR_BT_CYCLE_LENGTH_END+1, 1):
for cycle_pos in range(PAR_BT_N_POS_START, PAR_BT_N_POS_END+1, 1):
st.set_params(PAR_BT_START_CAPITAL, start_delay, cycle_length, cycle_pos, sBT,
iPAR_BT_TF1, iPAR_BT_TF2, iPAR_BT_TF3, iPAR_BT_TF4,
iPAR_BT_TFW1, iPAR_BT_TFW2, iPAR_BT_TFW3, iPAR_BT_TFW4)
st.reset()
bt = st.main()
# do something with return values (list) in bt
# after all processes have finished - use return values of all processes
将其作为多个流程进行工作的最佳方式是什么?
您可以从concurrent.futures
使用ProcessPoolExecutor
。
from concurrent.futures import ProcessPoolExecutor, as_completed
def run_strategy(*args):
st = Strategy(
st.set_params(*args)
st.reset()
bt = st.main()
return bt
ex = ProcessPoolExecutor()
futures = []
for start_delay in range(0, PAR_BT_CYCLE_LENGTH_END, 1):
for cycle_length in range(PAR_BT_CYCLE_LENGTH_START, PAR_BT_CYCLE_LENGTH_END+1, 1):
for cycle_pos in range(PAR_BT_N_POS_START, PAR_BT_N_POS_END+1, 1):
args = (
PAR_BT_START_CAPITAL,
start_delay,
cycle_length,
cycle_pos,
sBT,
iPAR_BT_TF1,
iPAR_BT_TF2,
iPAR_BT_TF3,
iPAR_BT_TF4,
iPAR_BT_TFW1,
iPAR_BT_TFW2,
iPAR_BT_TFW3,
iPAR_BT_TFW4
)
ex.submit(run_strategy, *args)
# collect the returned bts
bt_results = []
for f in as_completed(futures):
bt_results.append(f.result())
ex.shutdown()