How To Use Python Timeit Module Example

Python time.time() and time.clock() method can be used to calculate program execution time and cpu time. However, most of the time, we just want to count the execution time of some code fragments or algorithms. At this time, it is more convenient to use the timeit module. timeit module is a python built-in module for counting the execution time of small pieces of code. It also provides a command line calling interface.

1. Python timeit Module Methods Introduction.

1.1 timeit.timeit(stmt=’pass’, setup=’pass’, timer=, number=1000000, globals=None)

Create a timer instance and run the code for timing. By default, the code will be executed one million times.

  1. stmt : the code to be executed, in the form of a string, multiple code lines need multiple strings.
  2. setup : environment configuration before stmt execution, such as import statement.
  3. timer : timers in use.
  4. number : number of times of execution.
  5. globals : executed namespace.

1.2 timeit.repeat(stmt=’pass’, setup=’pass’, timer=, repeat=3, number=1000000, globals=None)

Execute the timeit.timeit method with specified number of repetitions and returns a list of results.

1.3 timeit.default_timer()

The default timer, which is also time.perf_ counter().

1.4 class timeit.Timer(stmt=’pass’, setup=’pass’, timer=, globals=None)

Timing class for code execution speed tests. This class has four methods.

  1. timeit(number=1000000).
  2. repeat(repeat=3, number=1000000).
  3. print_exc(file=None).
  4. autorange(callback=None)

2. How To Use timeit Module In Python Source Code Example.

Below are timeit module examples in python source code.

2.1 Basic Usage Of timeit Method.

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.6872886000001017
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.4593738999992638
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.31253259999903094

2.2 Set setup Parameters.

>>> import timeit

# run timeit method directly with setup parameter.
>>> timeit.timeit('char in text', setup='text = "sample string"; char = "g"')
0.1301296999990882

>>> timeit.timeit('text.find(char)', setup='text = "sample string"; char = "g"')
0.386987500001851

>>> t = timeit.Timer('char in text', setup='text = "sample string"; char = "g"')
>>> t.timeit()
0.1247934000020905

# the default repeat count is 5.
>>> t.repeat()
[0.1243577000022924, 0.11832910000157426, 0.11820590000206721, 0.11449139999967883, 0.12246040000172798]

# specify the repeat count to 2
>>> t.repeat(repeat=2)
[0.1236146999981429, 0.12262899999768706]

# specify the repeat count to 6
>>> t.repeat(repeat=6)
[0.12264829999912763, 0.11872610000136774, 0.11501510000016424, 0.12314899999910267, 0.12104419999741367, 0.12213300000075833]

2.3 Specify Calling Object Through The setup Parameter in timeit Method.

>>> def test():
...     L = [i for i in range(100)]
...
>>> if __name__ == '__main__':
...     import timeit
...     print(timeit.timeit("test()", setup="from __main__ import test"))
...
9.277826800000184

2.4 Test Multi-line Statement Execution Time.

>>> import timeit
>>> s = """\
... try:
...     str.__bool__
... except AttributeError:
...     pass
... """
>>> timeit.timeit(stmt=s, number=100000)
0.09223150000252645
>>>
>>># hasattr method execute more quickly than above method.
>>> s = "if hasattr(str, '__bool__'): pass"
>>> timeit.timeit(stmt=s, number=100000)
0.07005430000208435

2.5 Specify The Execution NameSpace Through The globals Parameter.

# define 3 functions.
>>> def f(x):
...     return x**2
...
>>> def g(x):
...     return x**4
...
>>> def h(x):
...     return x**8
...
>>> import timeit

# execute above 3 global namespace functions
>>> print(timeit.timeit('[func(42) for func in (f,g,h)]', globals=globals()))
3.298376200000348

3. How To Use timeit Module In Command Line.

Command Format : python -m timeit [-n N] [-r N] [-u U] [-s S] [-t] [-c] [-h] [ statement …]

  1. -n : number of execution time.
  2. -r : timer repeat execution time.
  3. -s : Execution environment configuration (usually the statement is only executed once).
  4. -h : help document.

4. Invoke timeit Module In Command Line Console Example.

Below are some examples of executing the timeit module on the command line.

4.1 Basic Usage timtit Module In Command Line.

# Windows Version
(env_python_37) C:\Users\zhaosong>python -m timeit "'-'.join([str(n) for n in range(100)])"
10000 loops, best of 5: 28.3 usec per loop

>python -m timeit -n 1000 "try:" "  str.__bool__" "except AttributeError:" "  pass"
1000 loops, best of 5: 729 nsec per loop

# Linux Or MacOS
>python -m timeit '"-".join([str(n) for n in range(100)])' 
10000 loops, best of 5: 28.3 usec per loop

# Windows Version
(env_python_37) C:\Users\zhaosong>python -m timeit "'-'.join(map(str, range(100)))"
20000 loops, best of 5: 15.6 usec per loop

# Linux Or MacOS
>python -m timeit "'-'.join(map(str, range(100)))"
20000 loops, best of 5: 15.6 usec per loop

4.2 Use Setup Parameters.

# Windows Version.
>python -m timeit -s "text = 'sample string'; char = 'g'"  "char in text"
2000000 loops, best of 5: 118 nsec per loop

# Linux And Mac OS Version.
python -m timeit -s 'text = "sample string"; char = "g"'  'char in text'

4.3 Test Multi-line Statement Execution Time.

# Windows Version.
>python -m timeit "try:" "  str.__bool__" "except AttributeError:" "  pass"
500000 loops, best of 5: 937 nsec per loop

# Linux And MacOS Version.
python -m timeit 'try:' '  str.__bool__' 'except AttributeError:' '  pass'

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.