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.
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.
]);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With