【问题标题】:Jupyter notebook, how to run multiple cells simultaneously?Jupyter notebook,如何同时运行多个单元?
【发布时间】:2019-05-11 21:44:24
【问题描述】:

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

>>> calc(1,2,3)

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

我想在 jupyter notebook 中同时运行多个 calc(x,y,z)s 和不同的 (x,y,z)s。正如您可能注意到的,问题在于 jupyter notebook 中的单元格是按顺序执行的。如果我运行三个calc 函数,它所花费的时间是一个函数运行时间的三倍。

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

  1. 使用multiprocessing模块:通过使用该模块,可以在“一个单元格”中同时执行多个calcs。但为了以后的分析,我想同时执行多个单元,其中仅包含一个 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 单元?

【问题讨论】:

    标签: python parallel-processing jupyter-notebook ipython


    【解决方案1】:

    在您的解决方案中,单元格按照您的预期由不同的引擎执行。该问题是由默认阻止行为引起的。您可以简单地添加--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 是执行单元后在笔记本中可见的单元执行编号。

    【讨论】:

      猜你喜欢
      • 2018-01-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-09-04
      • 2015-11-06
      相关资源
      最近更新 更多