You’re working on your script and want to see how fast a function would be. Here’s how to do that with the timeit module, included in the standard library.
Let’s say you have the following script:
import random
def sort_rand():
random.seed('pouet')
pool = [random.random() for i in range(1000)]
sorted_pool = sorted(pool)
return sorted_pool
if __name__ == "__main__":
sorted_nb = sort_rand()
And you want to check how fast sort_rand()
could be. Just add these 3 lines:
import random
def sort_rand():
random.seed('pouet')
pool = [random.random() for i in range(1000)]
sorted_pool = sorted(pool)
return sorted_pool
if __name__ == "__main__":
sorted_nb = sort_rand()
from timeit import Timer
print(Timer("sort_rand()", setup="from __main__ import sort_rand")
.repeat(repeat=3, number=1000))
This will print the time, in seconds, to run sort_rand()
1000 times, and repeat that 3 times.
The default number of calls if not provided is 1,000,000.
The output is a simple Python list with the elapsed time as a float, so you can call min()
, max()
and the likes to get the number the most meaningful to you.
Be sure to see the official doc for more info and examples.