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:
This will only measure how long that one%time sum(range(1000000))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:
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.%%time # This entire cell's execution will be timed numbers = [x * 3 for x in range(500000)] total = sum(numbers) print(f"Total: {total}") - Pro tip: If you forget to put
%%timeas the first line, Jupyter will throw an error, so make sure it's at the top before any other code.
Quick Recap
- Use
%timewhen you only need to time a single line of code. - Use
%%timewhen you want to profile the entire workflow in a cell (multiple lines, loops, function calls, etc.).
内容的提问来源于stack exchange,提问作者vbhargav875
相关产品推荐
相关产品推荐

