Python timeit module

Amansingh Javatpoint
2 min readMay 11, 2021

The timeit is a module of Python that helps developers to measure the time taken for the execution by the specific snippet of code. The timeit library of Python executes the code statement 1 million times and delivers the minimum time taken from the provided set of snippets of code. The timeit() function of Python appears to be a useful method that checks the code performance.

Let us understand the need for the timeit module.

What is the need for the timeit module?

  1. Unlike the simple time module, where the time is saved before and after the code execution and subtracts them, this module precisely monitors code execution time.
  2. The timeit() function executes the code millions of times (the default value is 1000000). Thus, it provides the statistically most relevant code execution time measurement.
  3. The timeit module is quite easy to utilize and has a command-line and callable interface.

Syntax of timeit() function

The Syntax of the timeit() function is given below.

Syntax:

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

These are the parameters of the timeit() function as follows:

  1. stmt: The stmt parameter will take the code for which we need the time of execution measurement. The default value of stmt is “pass“.
  2. setup: The setup parameter contains the details of the setup required to be run before stmt. The default value is of setup is also “pass“.
  3. timer: The timer parameter stores the value of the timer. Generally, the timeit() function already has a default value set, and therefore, we can ignore this parameter.
  4. number: The number parameter tells the function to execute stmt as per the number is provided. The default value is 1000000.

The timeit() function will return the time taken (in seconds) in order to execute the stmt, the particular number of times.

--

--