Why does Python's timeit() execute endlessly?
Asked Answered
P

2

5

When trying to use the Python built-in module 'timeit' as follows:

timeit.Timer('print "hi"').timeit()

it prints more than one line; why is that? It keeps printing "hi" endlessly:

hi
hi
hi
hi
...
Panicle answered 9/1, 2012 at 6:41 Comment(0)
V
14

timeit is designed to test extremely short code snippets, so it runs the code many times and averages them. As a default, it runs it 1000000 times.

You can change this by running it as follows:

timeit.Timer('print "hi"').timeit(number=1)
Venality answered 9/1, 2012 at 6:53 Comment(0)
O
8

If you look at the docs, you will see that the statement will default to executing 1000000 times.

If you only want to run it 2 times, you would pass a 2 to the timeit() method of the Timer class.

timeit.Timer('print "hi"').timeit(2)
Ossiferous answered 9/1, 2012 at 6:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.