Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 315
abeboparebop Avatar asked Oct 29 '22 12:10

abeboparebop


1 Answers

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.
        ]);
    });
});
like image 62
Louise Davies Avatar answered Nov 09 '22 11:11

Louise Davies