【问题标题】:How to enable timing magics for every cell in Jupyter notebook?如何为 Jupyter 笔记本中的每个单元启用计时魔法?
【发布时间】:2017-02-15 09:19:06
【问题描述】:

%%time%%timeit 魔法可以在 Jupyter 或 iPython 笔记本中对单个单元格进行计时。

是否有类似的功能可以为 Jupyter 笔记本中的每个单元打开和关闭计时?

This question 是相关的,但对于在每个单元格中自动启用给定魔法这一更普遍的问题没有答案。

【问题讨论】:

标签: python ipython-notebook jupyter-notebook


【解决方案1】:

通过 custom.js 文件(通常放在~/.jupyter/custom/custom.js)来实现这一点的一个hacky方法

如何为工具栏创建按钮的示例位于here,这是我此答案的依据。它只是在按下启用按钮时将您想要的魔法的字符串形式添加到所有单元格,禁用按钮使用str.replace 将其“关闭”。

define([
    'base/js/namespace',
    'base/js/events'
], function(Jupyter, events) {
    events.on('app_initialized.NotebookApp', function(){
        Jupyter.toolbar.add_buttons_group([
            {
                'label'   : 'enable timing for all cells',
                'icon'    : 'fa-clock-o', // select your icon from http://fortawesome.github.io/Font-Awesome/icons
                'callback': function () {
                    var cells = Jupyter.notebook.get_cells();
                    cells.forEach(function(cell) {
                        var prev_text = cell.get_text();
                        if(prev_text.indexOf('%%time\n%%timeit\n') === -1) {
                            var text  = '%%time\n%%timeit\n' + prev_text;
                            cell.set_text(text);
                        }
                    });
                }
            },
            {
                'label'   : 'disable timing for all cells',
                'icon'    : 'fa-stop-circle-o', // select your icon from http://fortawesome.github.io/Font-Awesome/icons
                'callback': function () {
                    var cells = Jupyter.notebook.get_cells();
                    cells.forEach(function(cell) {
                        var prev_text = cell.get_text();
                        var text  = prev_text.replace('%%time\n%%timeit\n','');
                        cell.set_text(text);
                    });
                }
            }
            // add more button here if needed.
        ]);
    });
});

【讨论】:

  • 很棒的答案,但我没有提到我在公司 Jupyter 服务器上运行,我不确定我是否可以访问 custom.js 来测试它。
  • 终于有机会在不同的系统上进行测试。如所写,答案没有多大意义——在每个单元格中同时拥有%%time%%timeit 是没有用的。所以无论你的答案是%%time\n%%timeit\n,我都用%%time\n 替换它。但是一般的方法效果很好。谢谢!
  • 顺便说一下,fa-clock-o 的图标有效,但 fa-stop-circle-o 无效。 Jupyter 核心版本 4.2.0。
猜你喜欢
  • 1970-01-01
  • 2017-11-04
  • 2017-02-27
  • 2017-09-24
  • 2017-10-25
  • 2020-04-05
  • 1970-01-01
  • 2013-05-28
  • 2017-01-19
相关资源
最近更新 更多