5.6 Measuring Execution Time
123
5.6 Measuring Execution Time
Even though computational speed should have low priority among beginners to
programming, it might be useful, at least, to have seen how execution time can be
found for some code snippet. This is relevant for more experienced programmers,
when it is required to find a particularly fast code alternative.
The measuring of execution time is complicated by the fact that a number
of background processes (virus scans, check for new mail, check for software
updates, etc.) will affect the timing. To some extent, it is possible to turn off such
background processes, but that strategy soon gets too complicated for most of us.
Fortunately, simpler and safer tools are available. To find the execution time of
small code snippets, a good alternative is to use the timeit module 12 from the
Python standard library.
5.6.1 The timeit Module
To demonstrate how this module may be used, we will investigate how function calls
affect execution time. Our brief “investigation” is confined to the filling of an array
with integers, done with and without a particular function call. The details are best
explained with reference to the following code (no timing yet!):
import numpy as np
def add(a, b):
return a + b
x = np.zeros(1000)
y = np.zeros(1000)
for i in range(len(x)):
x[i] = add(i, i+1)
# use function call to fill array
for i in range(len(x)):
y[i] = i + (i+1)
# ...no function call
So, the sum of two integers is assigned to each array element. The arrays x and y will
contain exactly the same numbers when the second loop is finished, but to fill x, we
use a call to the function add. Thus, the time to fill x is expected to take longer than
filling y, which just adds the numbers directly. Our question is, how much longer
does it take to use the function call?
To answer this question by use of timeit, we may write the script
timing_function_call.py:
import timeit
import numpy as np
def add(a, b):
return a + b
x = np.zeros(1000)
12 https://docs.python.org/3/library/timeit.html.
Précédent

- 144/350

Suivant