Introduction to Timeit module

This is module is used to see the time elapsed during a code execution. It is useful for small code snippets only.

Unlike time module, it avoids a number of common traps for measuring execution times.

As, we have discussed generators in the previous blog in that we covered that generators are less time to consume. If you want to go through that blog, just go to this link.

Here, in this blog, we will discuss Timeit module by taking an example of how much time is generally taken by generators and list comprehension.

Syntax:   timeit.timeit(‘Python code’ , number = no._of_repititions)

Now, will look at an example -:

import timeit

Checking time taken by generators using timeit

In [10]:
## If no. of repitions is less then less time
## no.of repitions = 500
# generator:

iterating_nums = (i+1 for i in range(6))''',number=500))
In [9]:
## If no. of repitions is more then more time

# generator:

iterating_nums = (i+1 for i in range(6))''',number=50000))

Checking time taken by list using timeit

In [12]:
## List comprehension is taking more time than generators

# list comprehension:

iterating_nums = [i+1 for i in range(6)]''',number=50000))

So, this is all for timeit module. Hope you understand the use of it.

Stay tuned for more amazing blogs. Keep learning Machine Learning with us.