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

Jupyter Notebook中%time与%%time的区别是什么?

Difference between %time and %%time in Jupyter Notebooks

Hey there! Let's break down exactly how these two magic commands differ—they're both great for timing your code, but they operate on totally different scopes:

%time (Line Magic)

  • This is a line-level magic command, meaning it only times the single line of code that immediately follows it.
  • Example usage:
    %time sum(range(1000000))
    
    This will only measure how long that one sum() call takes to run.
  • If you have multiple expressions on the same line (though not super common), it'll time the entire line's execution, but it's designed for single-line profiling.

%%time (Cell Magic)

  • This is a cell-level magic command, and it needs to be the very first line in your Jupyter cell. It times every line of code in the entire cell, from top to bottom.
  • Example usage:
    %%time
    # This entire cell's execution will be timed
    numbers = [x * 3 for x in range(500000)]
    total = sum(numbers)
    print(f"Total: {total}")
    
    Here, it'll measure the time taken to create the list comprehension, calculate the sum, and print the result—all wrapped into one total time.
  • Pro tip: If you forget to put %%time as the first line, Jupyter will throw an error, so make sure it's at the top before any other code.

Quick Recap

  • Use %time when you only need to time a single line of code.
  • Use %%time when you want to profile the entire workflow in a cell (multiple lines, loops, function calls, etc.).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 13:02:55