什么是python中的%timeit? [英] What is %timeit in python?
问题描述
我总是读取代码来计算这样的时间:
I always read the code to calculate the time like this way:
%timeit function()
你能在这里解释一下%的含义吗?
Can you explain what means "%" here?
我认为,%总是用于替换字符串中的某些内容,例如%s表示替换字符串,%d替换数据,但我没有关于这种情况的想法。
I think, the "%" is always used to replace something in a string, like %s means replace a string, %d replace a data, but I have no idea about this case.
推荐答案
%timeit
是 ipython magic 功能,可用于计时特定代码(单次执行)声明或单一方法)
%timeit
is an ipython magic function, which can be used to time a particular piece of code (A single execution statement, or a single method)
来自文档:
%timeit
%timeit
Time execution of a Python statement or expression
Usage, in line mode:
%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
要使用它,例如我们想要要确定使用 xrange
是否比使用范围
更快,您可以这样做:
To use it, for example if we want to find out whether using xrange
is any faster than using range
, you can simply do:
In [1]: %timeit for _ in range(1000): True
10000 loops, best of 3: 37.8 µs per loop
In [2]: %timeit for _ in xrange(1000): True
10000 loops, best of 3: 29.6 µs per loop
你会得到他们的时间。
主要优点是你没有必须导入 timer.timeit
,并多次运行代码以确定哪种方法更好; %timeit将根据总共2秒的执行窗口自动计算代码所需的运行次数。
The major advantage is that you don't have to import timer.timeit
, and run the code multiple times to figure out which is the better approach; %timeit will automatically calculate number of runs required for your code based on a total of 2 seconds execution window.
这篇关于什么是python中的%timeit?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!