124
5 Some More Python Essentials
y = np.zeros(1000)
# ...use the function add
t = timeit.Timer(’for i in range(len(x)): x[i] = add(i, i+1)’, \
setup=’from __main__ import add, x’)
x_time = t.timeit(10000)
# Time 10000 runs of the whole loop
print(’Time, function call: {:g} seconds’.format(x_time))
# ...no use of function add
t = timeit.Timer(’for i in range(len(y)): y[i] = i + (i+1)’, \
setup=’from __main__ import y’)
y_time = t.timeit(10000)
# Time 10000 runs of the whole loop
print(’Time: {:g} seconds’.format(y_time))
What will happen here? Well, first of all, note that there are two calls to
timeit.Timer, one for each of the two loops from above. If we look at the first
call to timeit.Timer, i.e.,
t = timeit.Timer(’for i in range(len(x)): x[i] = add(i, i+1)’, \
setup=’from __main__ import add, x’)
we notice that two arguments are provided. You may recognize the first argument,
for i in range(len(x)): x[i] = add(i, i+1), as a one-line version of the
first loop from above, i.e. the loop over x (usually, we prefer to write such loops not
on a single line. However, when used as an argument in a function call like here, the
one-line version is handy). This first argument, given as a string, is what we want
the timing of. The second argument, setup=’from __main__ import add, x’,
is required for initialization, i.e., what the timer needs to do prior to timing of the
loop. If you look carefully at the string-part of this second argument, you notice an
import statement for add and x. You may wonder why you have to do that when they
are defined in your code above, but stay relaxed about that, it is simply the way this
timer function works. What is required for the timer function to execute the code
given in the first argument, must be provided in the setup argument, even if it is
defined in the code above.
The following line,
x_time = t.timeit(10000)
# Time 10000 runs of the whole loop
will cause the whole loop to actually be executed, not a single time, but 10000
times! There will be one recorded time, the time required to run the loop 10000
times. Thus, if an average time for a single run-through of the loop is desired, we
must divide the recorded time by (in this case) 10000. Often, however, the total
time is fine for comparison between alternatives. The print command brings the
recorded time to the screen, before the next loop is timed in an equivalent way.
Why is the loop run 10000 times? To get reliable timings, the execution times
must be on the order of seconds, that is why. How many times the requested code
snippet needs to be run, will of course depend on the code snippet in question.
Sometimes, a single execution is enough. Other times, many more executions than
10000 are required. Some trial and error is usually required to find an appropriate
number.
Executing the program produces the following result,
Time, function call: 2.22121 seconds
Time: 1.4738 seconds
Précédent

- 145/350

Suivant