You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Jupyter Lab实时显示单元格运行时长?求插件或实现方案

解决方案

一、可用的现成插件

有一款jupyterlab-cell-execution-timer插件可以满足需求,它会在单元格运行过程中实时刷新显示已用时长,每秒更新一次HH:MM:SS格式的计时,运行结束后还会保留最终时长记录,无需手动计算。

安装方式:

pip install jupyterlab-cell-execution-timer
jupyter lab build

二、自定义插件实现思路

如果不想依赖现成插件,可基于Jupyter Lab的扩展API自行实现核心功能,核心步骤如下:

  • 监听单元格运行事件:通过Jupyter Lab的notebook模块,监听cell_executing事件,触发时记录当前时间戳(如Date.now())。
  • 定时更新计时显示:启动setInterval定时器,每秒计算当前时间与开始时间的差值,将毫秒数转换为时:分:秒的可读格式。
  • 插入显示元素:在单元格底部状态栏(即jupyterlab-execute-time显示开始时间的区域)添加新的DOM元素,用于展示实时更新的时长。
  • 清理资源:监听单元格运行结束的cell_executed事件,触发时清除定时器避免内存泄漏,同时可保留最终时长记录。

以下是核心逻辑的简化代码示例:

// 监听单元格开始运行事件
app.commands.commandRegistry.addCommand('custom-timer:start', {
  execute: async () => {
    const notebook = app.serviceManager.notebookTracker.currentWidget;
    const activeCell = notebook.activeCell;
    if (activeCell) {
      const startTime = Date.now();
      // 创建显示元素
      const timerElement = document.createElement('span');
      timerElement.className = 'custom-timer';
      activeCell.node.appendChild(timerElement);
      
      // 每秒更新计时
      const timer = setInterval(() => {
        const elapsed = Date.now() - startTime;
        const hours = Math.floor(elapsed / 3600000);
        const minutes = Math.floor((elapsed % 3600000) / 60000);
        const seconds = Math.floor((elapsed % 60000) / 1000);
        timerElement.textContent = `已运行: ${hours}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      }, 1000);
      
      // 运行结束时清除定时器
      activeCell.model.statusChanged.connect(() => {
        if (activeCell.model.status === 'idle') {
          clearInterval(timer);
        }
      });
    }
  }
});

注意:实际开发Jupyter Lab插件需遵循官方扩展规范,包括配置package.json、使用@jupyterlab/builder构建等,上述代码仅为核心逻辑演示。


内容的提问来源于stack exchange,提问作者Boppity Bop

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:15:48