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.
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.
# syntaxtimeit.timeit(stmt,setup,timer,number)
#Importing Libraryimport timeit#string of codecode='''def squaring():myList=[]for x in range(50):myList.append(sqrt(x))'''#timeit function using default timerprint(timeit.timeit(stmt=code,setup="from math import sqrt",number=10000))
repeat()
This function repeats the process of calculating the execution time for the specified code.
# syntaxtimeit.repeat(stmt,setup,timer,repeat,number)
#Importing Libraryimport timeit#string of codecode='''def squaring():myList=[]for x in range(50):myList.append(sqrt(x))'''#timeit function using default timerprint(timeit.repeat(stmt=code,setup="from math import sqrt",number=10000,repeat=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.
# syntaxtimeit.default_timer()
# Importing Libraryimport timeit# Importing sqrt functionfrom math import sqrt# string of codedef 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)
The constructor of this class takes three arguments: the statements to be timed, setup statements separated by ;
, and a timer function.
#syntaxClass timeit.Timer(stmt,setup,timer)
Flags | |
---|---|
- s | Setup |
- t | Time |
- r | Repeat |
- n | Number |