gpt4 book ai didi

python - Jupyter 笔记本,如何同时运行多个单元格?

转载 作者:行者123 更新时间:2023-11-28 18:57:50 24 4
gpt4 key购买 nike

我定义了一个运行 bash 脚本的 python 函数。假设函数是:calc(x,y,z)。如果我在 python 中使用一些变量运行这个函数,

>>> calc(1,2,3)

它生成使用变量(x=1, y=2, z=3) 模拟某些东西的 C 代码,编译 C 代码并执行编译后的输出文件。

我想在 jupyter notebook 中同时运行多个具有不同 (x,y,z)calc(x,y,z)。您可能已经注意到,问题在于 jupyter notebook 中的单元格是按顺序执行的。如果我运行三个 calc 函数,它需要比一个函数运行时间长三倍的时间。

我尝试了两种方法,但效果不佳。

  1. 使用multiprocessing模块:通过使用该模块,可以在“一个单元格”中同时执行多个calc。但为了以后的分析,我想同时执行多个单元,其中仅包含一个 calc,每个单元使用不同的处理器(或 cpu 内核)。
  2. 使用 ipyparallel 单元魔法(受此 answer 启发):我在导入 ipyparallel

    后尝试如下操作
    # Cell 1
    %%px --targets 0 # use processor 0
    calc(1,1,1)

    .

    # Cell 2
    %%px --targets 1 # use processor 1
    calc(2,2,2)

    .

    # Cell 3
    %%px --targets 2 # use processor 2
    calc(3,3,3)

但单元是按顺序执行的:单元 2 在单元 1 模拟完成后执行,与单元 3 类似。

如何使用不同的内核运行多个 jupyter 单元?

最佳答案

在您的解决方案中,单元按照您的预期由不同的引擎执行。该问题是由默认阻止行为引起的。您可以简单地添加 --noblock 参数以在非阻塞模式下执行单元格。然后单元格返回 AsyncResult 对象,一旦执行完成通过调用方法 display_outputs() 就可以读取输出。详情请查看文档 targets-and-blocking

# Cell 1
%%px --targets 0 --noblock
calc(1,1,1)

.

# Cell 2
%%px --targets 1 --noblock
calc(2,2,2)

.

# Cell 3
%%px --targets 2 --noblock
calc(3,3,3)

如果您需要访问输出,您可以调用 display_outputs(),正如我在上面解释的那样。

# output of the first the cell 1
___.display_outputs()

# output of the first the cell 2
__.display_outputs()

# output of the first the cell 1
_.display_outputs()

我使用下划线表示法访问单元格 1-3 返回的 AsyncResult 对象。还有许多其他方法可以访问这些对象,例如使用 Out[x],其中 x 是执行单元格后在笔记本中可见的单元格执行编号。

关于python - Jupyter 笔记本,如何同时运行多个单元格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56094492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com