Python timeit 不适用于 list.remove 操作

Python timeit doesn't works for list.remove operation

我试图通过 timeit 模块检查 python 列表中删除操作的性能,但它抛出一个 ValueError。

In [4]: a = [1, 2, 3]

In [5]: timeit a.remove(2)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-7b32a87ebb7a> in <module>()
----> 1 get_ipython().magic('timeit a.remove(2)')

/home/amit/anaconda3/lib/python3.4/site-packages/IPython/core/interactiveshell.py in magic(self, arg_s)
   2334         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2335         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2336         return self.run_line_magic(magic_name, magic_arg_s)
   2337 
   2338     #-------------------------------------------------------------------------

..
..
..
..

ValueError: list.remove(x): x not in list

您每次都需要创建列表,因为您在第一个循环后删除了 2:

In [2]: %%timeit
   ...: a = [1,2,3]
   ...: a.remove(2)
   ...: 

10000000 loops, best of 3: 159 ns per loop

您可以看到有 10000000 个循环,因此通过在 timeit 运行 之外创建列表,您删除了 2 第一个循环,因此在后续 运行s.

您可以计算列表创建的时间并减去它以获得删除所需时间的近似值。

In [3]: timeit a =  [1,2,3]
10000000 loops, best of 3: 89.8 ns per loop

你可以 运行 一次,但你的时间不会那么准确:

In [12]: a = [1,2,3]

In [13]: timeit -n 1 -r 1 a.remove(2)
1 loops, best of 1: 4.05 µs per loop

timeit 魔术命令的选项在 docs:

选项:

-n<N>: execute the given statement <N> times in a loop. If this value is not given, a fitting value is chosen.

-r<R>: repeat the loop iteration <R> times and take the best result. Default: 3

-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 <P> 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.