What is the Python timeit module?

The timeit module is a built-in library in Python programming. timeit is used to measure the execution time for the small python code snippets.

This module runs the code a million times (by default) to get the most precise value for the code execution time​.

Parameters

svg viewer

Functions

1. timeit()

This is a basic function which takes a small code as a string and runs it a million times to get the execution time.


Syntax

# syntax
timeit.timeit(stmt,setup,timer,number)

Example

#Importing Library
import timeit
#string of code
code='''
def squaring():
myList=[]
for x in range(50):
myList.append(sqrt(x))'''
#timeit function using default timer
print(timeit.timeit(stmt=code,setup="from math import sqrt",number=10000))

2. repeat()

This function repeats the process of calculating the execution time for the specified code.


Syntax

# syntax
timeit.repeat(stmt,setup,timer,repeat,number)

Example

#Importing Library
import timeit
#string of code
code='''
def squaring():
myList=[]
for x in range(50):
myList.append(sqrt(x))'''
#timeit function using default timer
print(timeit.repeat(stmt=code,setup="from math import sqrt",number=10000,repeat=3))

3. default_timer()

This function returns the waiting time along with the CPU time, and it’s dependent on the platform. Its value would be different for Windows, Linux, etc. Other programs running on the same computer may affect the output time.


Syntax

# syntax
timeit.default_timer()

Example

# Importing Library
import timeit
# Importing sqrt function
from math import sqrt
# string of code
def squaring():
myList=[]
for x in range(50):
myList.append(sqrt(x))
# time before the function starts.
start_time=timeit.default_timer()
squaring()
# calculating the time after function completes.
print(timeit.default_timer()-start_time)

Public Class

Timer

The constructor of this class takes three arguments: the statements to be timed, setup statements separated by ;, and a timer function.


Syntax

#syntax
Class timeit.Timer(stmt,setup,timer)

Command-Line Interface

svg viewer
Flags
- s Setup
- t Time
- r Repeat
- n Number
Copyright ©2024 Educative, Inc. All rights reserved