【发布时间】:2017-02-15 09:19:06
【问题描述】:
%%time 和 %%timeit 魔法可以在 Jupyter 或 iPython 笔记本中对单个单元格进行计时。
是否有类似的功能可以为 Jupyter 笔记本中的每个单元打开和关闭计时?
This question 是相关的,但对于在每个单元格中自动启用给定魔法这一更普遍的问题没有答案。
【问题讨论】:
标签: python ipython-notebook jupyter-notebook
%%time 和 %%timeit 魔法可以在 Jupyter 或 iPython 笔记本中对单个单元格进行计时。
是否有类似的功能可以为 Jupyter 笔记本中的每个单元打开和关闭计时?
This question 是相关的,但对于在每个单元格中自动启用给定魔法这一更普遍的问题没有答案。
【问题讨论】:
标签: python ipython-notebook jupyter-notebook
通过 custom.js 文件(通常放在~/.jupyter/custom/custom.js)来实现这一点的一个hacky方法
如何为工具栏创建按钮的示例位于here,这是我此答案的依据。它只是在按下启用按钮时将您想要的魔法的字符串形式添加到所有单元格,禁用按钮使用str.replace 将其“关闭”。
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.
]);
});
});
【讨论】:
custom.js 来测试它。
%%time 和%%timeit 是没有用的。所以无论你的答案是%%time\n%%timeit\n,我都用%%time\n 替换它。但是一般的方法效果很好。谢谢!
fa-clock-o 的图标有效,但 fa-stop-circle-o 无效。 Jupyter 核心版本 4.2.0。