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

冷暖自知 提交于 2019-12-05 17:45:15

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