gpt4 book ai didi

python - 如何为 Jupyter notebook 中的每个单元格启用计时魔法?

转载 作者:太空宇宙 更新时间:2023-11-03 11:21:26 27 4
gpt4 key购买 nike

%%time%%timeit 魔法可以在 Jupyter 或 iPython notebook 中为单个单元格计时。

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

This question是相关的,但没有回答更普遍的问题,即在每个单元格中自动启用给定的魔法。

最佳答案

一个 hacky 方法是通过 custom.js 文件(通常放在 ~/.jupyter/custom/custom.js 中)

如何为工具栏创建按钮的示例位于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.
]);
});
});

关于python - 如何为 Jupyter notebook 中的每个单元格启用计时魔法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42245170/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com