pythontimeit

How can Timer.timeit() takes a negative number as the argument?


The timeit(number=1000000) method of the Timer class in the stdlib's timeit module
can take a negative number as its argument, which doesn't make sense to me - what does the result even mean?

Example:

from timeit import Timer
t = Timer('pi * pi', setup='from math import pi')
t.timeit(-30) # <---

Solution

  • Check the source code of timeit module:

    class Timer:
        ...
        def timeit(self, number=default_number):
            ...
            it = itertools.repeat(None, number)
            ...
            try:
                timing = self.inner(it, self.timer)
            ...
    

    It's not hard to guess that it repeatedly executes code by iterating itertools.repeat(None, number). A simple test will tell what will happen:

    >>> from itertools import repeat
    >>> list(repeat(None, -1))
    []
    

    So you can know, when number is a negative parameter, it is an empty iterable object, so Timer will not run the code to be tested.