Python is a high-level language that is general purpose and is simple in nature that emphasizes the readability of code and follows such a syntax that allows programmers to develop software using fewer lines of code.

Some features of Python include:

  • Quickly integrate systems to work with code efficiently.
  • It is multi-purpose, high-level, object-oriented, and procedural in nature.
  • It is simpler and smaller than other programming languages comparatively.

In this article, we will be discussing the Python timeit() function that is used to measure the execution time of our Python code.

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

What Is Python timeit()?

It is an in-built function in Python used to measure the time taken to execute a small bit of Python code.  

Syntax 

timeit.timeit(setup = <value>,

                     stmt = <value>,

                     number = <value>,

timer=<value>)

Parameters

→ setup: code that needs to run before stmt. The default value is ‘pass’.

→ timer: timeit.Timer object. Has a random default value.

→ stmt: Statement that needs to be measured. Default is ‘pass’.

→ number: Number of executions that we want the stmt to run.

Example

Code

# testing the timeit()

import timeit

import_module = "import random"

testingcode = ''' 

def test(): 

    return random.randint(10, 50)

print(timeit.timeit(stmt=testingcode, setup=import_module))

Output

23.546672345623214

Methods in timeit() Using Python

There are different types of methods that can be executed using timeit() in Python. Some of them are explained below:

timeit.default_timer

This method will directly return the time that is the default when it is executed.

Example

import timeit

import random

def test(): 

    return random.randint(10, 50) 

starting_time = timeit.default_timer()

print("Start time :",starting_time)

test()

print("Time difference :", timeit.default_timer() - starting_time)

Output

Start time : 38715.518857217

Time difference : 5.9070996940135956e-05

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

It is similar to timeit(), but it executes the same by the number of times the repeat is given.

Example 1

import timeit

import_module = "import random"

testcode = ''' 

def test(): 

    return random.randint(10, 50)

'''

print(timeit.repeat(stmt=testcode, setup=import_module, repeat=8))

Output

[0.08171100300023681, 0.08849931000077049, 0.09055445500052883, 0.08828036399791017, 0.09204522100117174, 0.10821463699903688, 0.09858635899945511, 0.09128028399936738]

Note: The timeit.repeat() function is identical to the timeit.timeit() function in that it accepts the repeat argument and returns the execution time in an array format with values based on the repeat number.

Example 2

import timeit

# binary search function implementation

def binary_search_func(list1, x):

    while len(list1) > 0:

        mid = (len(list1))//2

        if list1[mid] == x:

            return True

        else if list1[mid] < x:

            list1 = list1[:mid]

        else:

            list1 = list1[mid + 1:]

    return False

# linear search function implementation

def linear_search_func(list2, y):

    for x in list2:

        if x == y:

            return True

    return False

# computing the binary search time

def binary_time_compute():

    INITIAL_CODE = '''

from __main__ import binary_search

from random import randint'''

    TESTING_CODE = '''

list3 = [x for x in range(5000)]

z = randint(0, len(list3))

binary_search_func(list3, z)'''    

    # timeit.repeat statement implementation

    times = timeit.repeat(setup = INITIAL_CODE,

                          stmt = TESTING_CODE,

                          repeat = 4,

                          number = 5000)

    # printing the minimum exec. time

    print('Binary search: {}'.format(min(times)))        

# computing linear search time

def linear_time_compute():

    INITIAL_CODE = '''

from __main__ import linear_search

from random import randint'''    

    TESTING_CODE = '''

list4 = [x for x in range(10000)]

w = randint(0, len(list4))

linear_search(list4, w)

    '''

    # timeit.repeat statement implementation

    times = timeit.repeat(setup = INITIAL_CODE,

                          stmt = TESTING_CODE,

                          repeat = 4,

                          number = 5000) 

    # printing the minimum exec. time

    print('Linear search: {}'.format(min(times)))  

if __name__ == "__main__":

    linear_time_compute()

    binary_time_compute()

Output

Linear search time: 6.69415425228

Binary search time: 5.8807977777

Why Is timeit() the Best Way to Measure the Execution Time of Python Code?

There are a few reasons why timeit() is the best way to measure the execution time, and some of these are given below:

  • It repeats the code statement 1 million times, which is the default setting, and then returns the shortest time. The parameter number in the time () function can also be used to increase or decrease the 1 million.
  • The garbage collection gets disabled every time the test is run via the time () function.

Internally, timeit() calculates the correct time based on the operating system you're using. For example, for Windows, it will use time.clock() while for Mac and Linux, it will use time.time().

Want a Top Software Development Job? Start Here!

Full Stack Developer - MERN StackExplore Program
Want a Top Software Development Job? Start Here!

Learn Python In-Depth With Simplilearn

The Python timeit() function is used to find the execution time of the Python code snippets. 

There are two methods in Python timeit():

  • timeit.default_timer
  • timeit.repeat(stmt, setup, timer, repeat, number)

To know more about Python and its various concepts, you would want a comprehensive course to guide you through this journey of learning and understanding Python and its various features and functions to build efficient software. Enroll in Simplilearn’s Post Graduate Program in Full Stack Web Development to get thorough guidance in Python to build efficient and reliable applications and programs using Python.

Our Software Development Courses Duration And Fees

Software Development Course typically range from a few weeks to several months, with fees varying based on program and institution.

Program NameDurationFees
Caltech Coding Bootcamp

Cohort Starts: 17 Jun, 2024

6 Months$ 8,000
Full Stack Developer - MERN Stack

Cohort Starts: 24 Apr, 2024

6 Months$ 1,449
Automation Test Engineer

Cohort Starts: 1 May, 2024

11 Months$ 1,499
Full Stack Java Developer

Cohort Starts: 14 May, 2024

6 Months$ 1,449