Timeit in Python with Examples
Last Updated :
28 Apr, 2025
The timeit module in Python accurately measures the execution time of small code snippets, offering more consistent results than time.time() by avoiding background interference and disabling garbage collection. It’s ideal for comparing code performance, benchmarking and optimization and can be used via the command line, in scripts or within code. Example:
Python
import timeit
a = "5+5"
print(timeit.timeit(a))
Output0.015736839000055625
Explanation: timeit.timeit(a) measures how long it takes to execute the expression "5+5" one million times by default.
Python timeit syntax
timeit.timeit(stmt, setup, timer, number)
Parameter:
- stmt: The code you want to time (as a string)
- setup: Setup code that runs before timing (as a string).
- timer: Timer function (default is fine).
- number: Number of times to execute stmt.
Returns: It returns the number of seconds it took to execute the code.
Python timeit examples
Example 1: We can pass multiple lines of code in a single string by separating them with semicolons (;). This is useful when timing short snippets of code using timeit.timeit().
Python
import timeit
a = timeit.timeit(stmt='x=15; y=15; sum=x+y')
print(a)
Output0.03771957599974485
Explanation: timeit.timeit() measures the total time to execute a code snippet, here assigning values to x and y and calculating their sum, run 1,000,000 times by default using semicolon separated statements in the stmt parameter.
Example 2: We can also pass a function directly to timeit.timeit() without wrapping it in a string. This makes your code cleaner and avoids using the stmt and setup strings.
Python
import timeit
from math import sqrt
def example():
a = [sqrt(x) for x in range(100)]
print(timeit.timeit(example, number=10000))
Output0.11834059100010563
Explanation: timeit.timeit() measures the total time to run the example function 10,000 times, where each run generates a list of square roots from 0 to 99 using list comprehension.
Example 3: We can use timeit.repeat() to run the same timing test multiple times and get a list of results. This is useful for observing variability in execution time due to system load or randomness.
Python
import timeit
from random import randint
def fun(lst, target):
return target in lst
print(min(timeit.repeat(
lambda: fun(list(range(10000)), randint(0, 10000)),
repeat=3, number=10000
)))
Output
0.7208773000002111
Explanation: timeit.repeat() measures how long the fun function takes to check if a random target exists in a list of 10,000 elements. It runs this 10,000 times per repeat for 3 repeats .
Example 4: We manually measure the start and end time of a code block. This is helpful when you want more control over what you're timing.
Python
import timeit
import random
def fun():
return random.randint(100, 800)
t1 = timeit.default_timer()
fun()
t2 = timeit.default_timer()
print(t2-t1)
Output8.594999599154107e-06
Explanation: timeit.default_timer() records start and end times around the fun function and their difference gives the time taken for a single execution.
Example 5: We can also use the timeit module directly from the command line to quickly benchmark simple Python statements without writing a full script.
Python
python -m timeit -s "import math" "math.sqrt(25)"
Output
Terminal outputExplanation: This command times how long math.sqrt(25) takes to run, importing math once with -s and uses timeit's default settings to report total execution time.
Similar Reads
Python datetime.timetz() Method with Example The timetz() function manipulates the objects of the DateTime class of the DateTime module. This function uses an instance method given to it via reference, and converts them, and returns a time object with the same hour, minute, second, microsecond, and fold and tzinfo attributes. Syntax: timetz()
3 min read
Working With Dates in Python In this article, we will discuss how to work with dates using python. Python makes dealing with dates and time very easy, all we have to do is import a module named DateTime that comes along with python. It is a more efficient way to work with date without the need of being explicitly programmed. By
4 min read
Python timedelta total_seconds() Method with Example The total_seconds() function is used to return the total number of seconds covered for the specified duration of time instance. This function is used in the timedelta class of module DateTime. Syntax: total_seconds() Parameters: This function does not accept any parameter. Return values: This functi
2 min read
Time tuple in Python Prerequisites: Python datetime module with examples In Python, the datetime module is used to operate with date and time objects. This module has different functions and classes for working with date and time parsing, formatting and arithmetic operations. The datetime module has various constants su
3 min read
Python DateTime - time.replace() Method with Example In this article, we will discuss the time.replace() method in Python. This method is used to manipulate objects of time class of module datetime. It is used to replace the time with the same value, except for those parameters given new values by whichever keyword arguments. Syntax: replace(year=self
2 min read
Python | time.time_ns() method Time module in Python provides various time-related functions. This module comes under Pythonâs standard utility modules. time.time_ns() method of Time module is used to get the time in nanoseconds since the epoch. To get the time in seconds since the epoch, we can use time.time() method. The epoch
2 min read