如何为Jupyter笔记本中的每个单元启用计时魔术? [英] How to enable timing magics for every cell in Jupyter notebook?

查看:293
本文介绍了如何为Jupyter笔记本中的每个单元启用计时魔术?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

%%time%%timeit魔术使Jupyter或iPython笔记本中的单个单元格计时.

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

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

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.

推荐答案

一种骇人听闻的方法是通过custom.js文件(通常放置在~/.jupyter/custom/custom.js中)

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

这篇关于如何为Jupyter笔记本中的每个单元启用计时魔术?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆