Python timeit doesn't works for list.remove op

2019-02-27 01:26发布

问题:

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.