IPython(jupyter环境)中的”魔法“命令 %time,%timeit,%%time,%%timeit

IPython(jupyter环境)中的”魔法“命令 %time,%timeit,%%time,%%timeit

前言:

这一部分原打算写在应该自己的Python OpenCV速度提升全汇总这篇博客里的,但这些命令只是单纯用来分析代码时间。如果加在那篇代码里的话,可能就会显得太冗长了。所以单独写出来了。

正文

个人理解

%代表着线模式,%%代表单元格模式。
%time和%%time代表的是这个语句执行这一次所用的时间
%timeit和%%timeit代表的是这个语句多次执行的单次平均时间。所以timeit更精准可控,而time更方便。

官方详细介绍

原文搬运,非常推荐大家去这里
IPython官方文档内置魔术命令的介绍
看原文,当然这两个部分我先搬运过来,方便大家理解哈。如果不想看这些,可以直接看下一节举例说明,那里会清晰详细的解释给大家看

time

Time execution of a Python statement or expression.

The CPU and wall clock times are printed, and the value of the expression (if any) is returned. Note that under Win32, system time is always reported as 0, since it can not be measured.

This function can be used both as a line and cell magic:

In line mode you can time a single-line statement (though multiple ones can be chained with using semicolons).

In cell mode, you can time the cell body (a directly following statement raises an error).

This function provides very basic timing functionality. Use the timeit magic for more control over the measurement.

timeit

Time execution of a Python statement or expression

Usage, in line mode:
%timeit [-n -r [-t|-c] -q -p

-o] statement

or in cell mode:
%%timeit [-n -r [-t|-c] -q -p

-o] setup_code code code…

Time execution of a Python statement or expression using the timeit module. This function can be used both as a line and cell magic:

In line mode you can time a single-line statement (though multiple ones can be chained with using semicolons).

In cell mode, the statement in the first line is used as setup code (executed but not timed) and the body of the cell is timed. The cell body has access to any variables created in the setup code.

Options: -n: execute the given statement times in a loop. If is not provided, is determined so as to get sufficient accuracy.

-r: number of repeats , each consisting of loops, and take the best result. Default: 7

-t: use time.time to measure the time, which is the default on Unix. This function measures wall time.

-c: use time.clock to measure the time, which is the default on Windows and measures wall time. On Unix, resource.getrusage is used instead and returns the CPU user time.

-p< P>: use a precision of

digits to display the timing result. Default: 3

-q: Quiet, do not print result.

-o: return a TimeitResult that can be stored in a variable to inspect
the result in more details.

The times reported by %timeit will be slightly higher than those reported by the timeit.py script when variables are accessed. This is due to the fact that %timeit executes the statement in the namespace of the shell, compared with timeit.py, which uses a single setup statement to import function or create variables. Generally, the bias does not matter as long as results from timeit.py are not mixed with those from %timeit.

举例说明

再用例子来解释下上面的文档。
首先是无关的例子,经常使用的time模块。

import time
t1=time.time()
test_work=[x**2 for x in range(1,1000000,3)]
t2=time.time()
print(t2-t1)

 
  • 1
  • 2
  • 3
  • 4
  • 5

输出
无关例子
好的,我们步入主题。

time

这个比较简单

%time test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1

输出
%time例子

%%time
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1
  • 2
  • 3
  • 4

输出
%%time例子
time模块的话会返回两个时间,一个是CPU times,另一个是Wall time。
如果你对CPU times和Wall time。不太理解。建议看这篇博客。
CPU time与WALL time
文档指出在WIN32系统中sys时间总是为0,因为没法被测量。

timeit
%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o]#线模式
%%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o]#单元格模式

 
  • 1
  • 2

还是从最简单的开始

%timeit test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1

输出
%timeit最简单例子
接着我们加这些东西
先列出这些参数是啥。
-n :在循环中执行给定语句次。如果未提供,则确定以获得足够的精度。%timeit默认值为10,%%timeit的默认值为1
-r :重复次数,每个重复次数由个循环组成,并获得最佳结果。默认值均为7
-t:使用time.time来测量时间,这是Unix上的默认值。此功能测量墙壁时间。
-c:使用time.clock来测量时间,这是Windows上的默认设置,用于测量墙壁时间。在Unix上,使用resource.getrusage代替并返回CPU用户时间。
-p < P>:使用

位的精度显示计时结果。默认值均为:3
-q:安静,不打印结果。
-o:返回一个TimeitResult,可以将其存储在变量中以进行检查

我们先加-n和-r。

%timeit -n30 -r10 test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1

输出
%timeit只加n和r
上面那张图我们可以看到改动后对返回的值的影响
接着改动 -p 和 选择-t或者-c。

%timeit -n30 -r10 -p5 -c test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1

%timeit -n30 -r10 -p5 -t test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1

输出:-p-c-t
至于-q,我加了,果然真的quiet了。

接着说%%timeit.

%%timeit
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1
  • 2
  • 3
  • 4

输出
%%timeit例子
还是加-r -n -c/-t -p

%%timeit -n30 -r10
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1
  • 2
  • 3
  • 4

输出
在这里插入图片描述

%%timeit -n30 -r10 -p5 -c 
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1
  • 2
  • 3
  • 4

输出
在这里插入图片描述

%%timeit -n30 -r10 -p5 -t 
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]
test_work=[x**2 for x in range(1,1000000,3)]

 
  • 1
  • 2
  • 3
  • 4

输出
在这里插入图片描述

结束语

感谢看到这里,不懂的地方欢迎留言。

<think> 首先,用户的问题是关于如何使用Python%timeit来比较性能。具体来说,用户问:“请问Python中使用%timeit比较性能的方法”。我需要基于提供的引用来回答。 回顾引用: - 引用[1]: 解释了%timeit用于一行代码的运行时间,%%timeit用于整个cell的代码运行时间。它还提到了其他模块如timeit.timeit、time.clock()和time.time()。 - 引用[2]: 对比了%%time, %time, 和 %timeit%%time%time给出代码运行一次的时间,而%timeit运行多次并给出平均时间。 - 引用[3]: 突出了%timeit用于微秒或纳秒级语句的性能比较,并给出了一个例子比较字符串操作。 系统级指令: - 我必须使用$...$格式的行内数学表达式,但这里似乎不需要数学表达式,因为主题是Python性能测试。 - 独立公式用$$...$$格式单独成段,同样,可能不需要。 - LaTeX语法正确。 - 使用中文回答。 - 生成相关问题。 - 在引用的段落末尾添加引用标识如[^1]。 用户可见层指令: - 回答结构清晰,逐步解决问题。 - 保证回答真实可靠。 - 参考用户上一次的问题:用户想了解如何使用%timeit来比较性能。 我的回答结构: 1. **引言**:简要解释%timeit是什么及其用途。 2. **方法**:逐步说明如何使用%timeit。 3. **示例**:基于引用提供代码示例。 4. **比较与其他工具**:简要对比%timeit与其他性能测试方法。 5. **注意事项**:给出使用建议。 6. **相关问题**:生成相关问题。 关键点从引用中提取: - %timeit用于测量代码执行时间,在IPythonJupyter Notebook中可用。 - 它运行代码多次(默认100,000次)并计算平均时间。 - 与%time相比,%timeit更精确用于短时间操作。 - 示例:如引用[2]和[3]中的代码片段。 生成相关问题: - 系统指令要求生成相关问题。 - 基于主题,创建2-3个相关问题,放在最后。 引用标识: - 在回答中引用特定信息时,在段落末尾添加引用标识。 最终回答大纲: - **开头**:直接回答问题。 - **步骤**: 1. 如何在Jupyter Notebook中使用%timeit。 2. 参数调整(如运行次数)。 3. 比较不同代码的性能。 - **示例代码**:展示比较两个字符串操作的例子(从引用[3])。 - **结尾**:总结优势。 - **相关问题**。 </think> ### Python中使用%timeit比较性能的方法 为了帮助您理解如何使用Python%timeit来比较代码性能,我将基于引用内容进行结构化说明。%timeitIPythonJupyter Notebook中的魔法命令(Magic Command),主要用于测量短代码片段的执行时间,特别适用于微秒或纳秒级的操作。它通过多次运行代码并计算平均时间来提高精度,避免了单次运行的偶然性误差。以下是详细使用方法,参考了提供的引用内容。 #### 1. **%timeit的基本用法** %timeit用于测量一行代码或一个代码单元的性能。核心步骤如下: - **测量一行代码**:直接在代码前添加`%timeit`命令。它会自动运行代码多次(默认100,000次),并输出平均时间和标准差。例如: ```python %timeit [x for x in range(1000)] # 测量列表推导式的性能 ``` 输出示例:`100000 loops, best of 5: 3.22 µs per loop`,表示运行100,000次后的平均时间[^2]。 - **测量多行代码(整个cell)**:如果代码跨越多行,使用`%%timeit`命令放在cell的开头。它会测量整个cell的执行时间。例如: ```python %%timeit li = [] for i in range(1000): li.append(i ** 2) # 测量循环结构的性能 ``` 输出示例:`321 µs ± 2.03 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)`,其中“±”表示标准差,反映时间波动[^2]。 这种方法比单次计时工具(如`%time`或`time.time()`)更可靠,因为它减少了系统波动的影响[^1]。 #### 2. **比较不同代码的性能** 要比较多个版本的代码,请连续使用%timeit命令测量每个版本,并分析输出结果。关键点是: - **输出解读**:关注“per loop”后的平均时间(如`267 ns`)和标准差(如`± 2.03 µs`)。较小的平均时间和较低的标准差表示性能更好。 - **基准测试示例**:参考引用[3]的例子,比较字符串操作的两种方法: ```python x = 'foobar' y = 'foo' %timeit x.startswith(y) # 方法1:使用startswith函数 %timeit x[:3] == y # 方法2:使用切片比较 ``` 输出可能类似: ``` 1000000 loops, best of 3: 267 ns per loop # 方法1较慢 10000000 loops, best of 3: 147 ns per loop # 方法2更快 ``` 这里,方法2的平均时间(147 ns)明显低于方法1(267 ns),表明切片操作性能更优[^3]。 - **调整运行次数**:对于极短的操作,可增加运行次数以提高精度。使用`-n`参数指定循环次数,或`-r`参数指定运行轮数: ```python %timeit -n 1000000 x.startswith(y) # 运行100万次 ``` 默认设置通常足够,但针对复杂代码,增加次数能减少方差[^1]。 #### 3. **与其他工具的对比** %timeit优于其他计时方法,尤其适合精细性能比较: - **vs %%time/%time**:%%time%time只测量单次运行时间(输出如`Wall time: 0 ns`),适合宏观分析,但对微秒级操作不敏感。%timeit通过多次平均,提供更稳定的结果[^2]。 - **vs timeit.timeit**:Python标准库的`timeit.timeit`函数功能类似,但%timeitJupyter中更易用,无需导入模块或设置复杂环境[^1]。 - **vs time.clock()/time.time()**:这些传统方法需手动编写循环和计时逻辑,容易引入误差,%timeit自动化处理更可靠[^1]。 #### 4. **使用建议** - **适用场景**:%timeit最适合短小代码片段(如函数调用、循环或表达式),避免用于长时间运行的程序。 - **注意事项**:确保代码无副作用(如不修改全局变量),因为它会多次执行。在Jupyter Notebook中,%timeit是首选工具,因为它集成度高、语法简洁[^1]。 - **最佳实践**:比较性能时,保持环境一致(如重启内核后测试),以减少后台干扰。输出中的“std. dev.”(标准差)值较低表明结果可靠。 总之,%timeit通过自动化多次运行和平均计算,为Python代码提供高效、可靠的性能比较。引用内容强调,它是Jupyter用户的首选工具,尤其适合优化算法或函数[^1][^2][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值