First Example

Here is a simple example of timeit() function

Code Example 1:

Output: We have seen a simple example that gives us the execution time of the simple code statement output = 10*5, and the time is taken to execute it is 0.06127880399999999.

Timing Multiple lines in python code

There are two you can execute multiple lines of code in timeit.timeit(), using a semicolon or by saving the code enclosed as a string with triple quotes. Here are examples that show the working of it.

Example 1: Using semicolon

Output:

Example 2: Using triple quotes

Output:

timeit – Methods:

Here, are 2 important timeit methods timeit.default_timer() : This will return the default time when executed. timeit.repeat(stmt, setup, timer, repeat, number) : same as timeit() , but with repeat the timeit() is called the number of times repeat is given.

Program Example 1:

Output:

Example 2:

default_timer() Example Output:

Example 3: timeit.repeat()

Output: timeit.repeat() works similar to timeit.timeit() function, with the only difference it takes in the repeat argument and gives back the execution time in array format with values as per the repeat number.

Executing timing function timeit.timeit() inside command-line interface

The syntax to execute your function inside timeit() on the command line is as follows:

-n N: the number of times you want the code to execute. -r N: the number of times you want the timeit() function to repeat -s S: this will have setup details that will get executed before code execution. -t: for this, you can make use of time.time() -c: for this, you can make use of time.clock() -h: for help code statement: The code details.

Example:

Another way you can execute inside command line is as shown below:

Example :

Why is timeit() the best way to measure the execution time of Python code?

Here are a few reasons why we consider timeit() is the best way to measure execution time.

It runs the code statement 1 million times that is the default value, and from that, it will return you the minimum time taken. You can also increase/decrease the 1 million by setting the argument number in time () function. While executing the test, the garbage collection is disabled every time by time () function. timeit() internally takes the accurate time as per your operating system being used. For example, it will use time.clock() for Windows operating system and time.time() for mac and Linux.

Summary

Timeit()is used to get the execution time taken for the small code given Parameters used with timeit()

stmt: This will take the code you want to measure the execution time setup: This will have setup details that need to be executed before stmt timer: This will have the timer value, timeit() already has a default value set, and we can ignore it. number: The stmt will execute as per the number is given here.