如何为 Jupyter notebook 中的每个单元启用计时魔法?

abe*_*bop 5 python ipython-notebook jupyter-notebook

%%time%%timeit魔法使得能够在Jupyter或IPython的笔记本单个小区的定时。

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

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

Lou*_*ies 2

一种巧妙的方法是通过 custom.js 文件(通常放置在~/.jupyter/custom/custom.js

如何为工具栏创建按钮的示例位于此处,这就是我这个答案的基础。它只是在按下启用按钮时将您想要的魔法的字符串形式添加到所有单元格,而禁用按钮则用于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.
        ]);
    });
});
Run Code Online (Sandbox Code Playgroud)