Python timeit doesn't works for list.remove operation

半世苍凉 提交于 2019-12-20 02:34:44

问题


I was trying to check the performance of remove operation in python list through the timeit module, but it throws a 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

回答1:


You need to create the list each time as you have removed the 2 after the first loop:

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

10000000 loops, best of 3: 159 ns per loop

You can see there were 10000000 loops so by creating the list outside the timeit run you removed 2 the first loop so there is no 2 to remove on subsequent runs.

You can time the list creation and subtract that to get an approximation of the time it takes to just remove.

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

You could run it once but your timings won't be near as accurate:

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

The options for timeit magic command are in the docs:

Options:

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



来源:https://stackoverflow.com/questions/34092508/python-timeit-doesnt-works-for-list-remove-operation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!