将迭代转换为映射

2024-05-19 06:22:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

@classmethod
def load(self):
    with open('yaml/instruments.yaml', 'r') as ymlfile:
        return {v['name']: Instrument(**v) for (v) in list(yaml.load_all(ymlfile))}

我想用如下方式并行加载这些文件:

return ThreadPoolExecutor.map(Instrument, list(yaml.load_all(ymlfile))

但我不太清楚如何让参数通过。你知道吗

下面是一个仪器.yaml地址:

---
    name: 'corn'
    #Trade December corn only
    multiplier: 5000
    contract_prefix: 'C'
    months_traded: [3, 5, 7, 9, 12]
    quandl: 'CHRIS/CME_C2'
    first_contract: 196003
    backtest_from: 199312
    trade_only: [12]
    contract_name_prefix: 'C'
    quandl_database: 'CME'
    slippage: 0.125 #half the spread
    ib_code: 'ZC'

如何将代码重构为映射,以便使用ThreadPoolExecutor?你知道吗


Tags: 代码nameyamlonlyprefixreturnloadall
1条回答
网友
1楼 · 发布于 2024-05-19 06:22:08

简单的解决方案是定义一个顶级的简单辅助函数,以便在executor中使用:

def make_instrument_pair(d):
    return d['name'], Instrument(**d)

然后更改:

@classmethod
def load(self):
    with open('yaml/instruments.yaml', 'r') as ymlfile:
        return {v['name']: Instrument(**v) for (v) in list(yaml.load_all(ymlfile))}

收件人:

@classmethod
def load(self):
    with open('yaml/instruments.yaml') as ymlfile,\
         concurrent.futures.ThreadPoolExecutor(8) as executor:
        return dict(executor.map(make_instrument_pair, yaml.load_all(ymlfile)))

正如我在评论中指出的,这可能不会给您带来任何好处;the GIL意味着线程不会提高性能,除非:

  1. 这项工作是在第三方C扩展中完成的,该扩展在执行大量C级工作之前显式地发布GIL
  2. 工作主要是I/O绑定的(或者以某种方式花费大部分时间阻塞,不管是睡眠、等待锁等)

除非Instrument的构造成本非常高,否则即使使用ProcessPoolExecutor也不会有帮助;您需要在分派的任务中做大量有意义的工作,或者您在任务管理(以及进程、序列化和进程间通信)上的时间比并行性上的时间要多。你知道吗

相关问题 更多 >

    热门问题