How to enable timing magics for every cell in Jupyter notebook?

梦想与她 提交于 2019-12-07 10:31:35

问题


The %%time and %%timeit magics enable timing of a single cell in a Jupyter or iPython notebook.

Is there similar functionality to turn timing on and off for every cell in a Jupyter notebook?

This question is related but does not have an answer to the more general question posed of enabling a given magic automatically in every cell.


回答1:


A hacky way to do this is via a custom.js file (usually placed in ~/.jupyter/custom/custom.js)

The example of how to create buttons for the toolbar is located here and it's what I based this answer off of. It merely adds the string form of the magics you want to all cells when pressing the enable button, and the disable button uses str.replace to "turn" it off.

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.
        ]);
    });
});


来源:https://stackoverflow.com/questions/42245170/how-to-enable-timing-magics-for-every-cell-in-jupyter-notebook

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!