Python timeit(): How to Time Your Code (2025)
By Rohit Sharma
Updated on Apr 24, 2025 | 20 min read | 1.5k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Apr 24, 2025 | 20 min read | 1.5k views
Share:
Table of Contents
The Python timeit() function helps you identify slow parts of your code, enabling better optimization decisions. It runs code up to 1,000,000 times by default and measures code performance.
Python provides several ways to measure execution time, but the timeit module in Python stands out due to its precision and reliability. It eliminates common pitfalls such as system variations, background processes, and startup overhead, ensuring accurate benchmarking.
This blog guides you through what timeit in Python is, how to use it on the command line, and how it helps in profiling.
timeit is a built-in module in Python that enables you to measure the execution time of small code snippets accurately. It is explicitly designed for benchmarking code by minimizing the impact of external factors, such as CPU load, background processes, or system interruptions. Unlike the time() function, which can be imprecise due to such noise, timeit provides a more controlled environment for performance testing.
By default, it runs the code snippet one million times, ensuring consistent and reliable results. This makes timeit particularly useful when fine-tuning functions or comparing different implementations of the same logic.
For example, if you're deciding between using a list comprehension or a traditional for loop, timeit can help you determine which option is faster in practice.
Real-World Scenarios:
Understanding the syntax correctly will help you customize timeit() for your specific use case. Below is the syntax for Python’s timeit() function, along with an explanation of each argument it expects.
Syntax:
import timeit
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>,
number=1000000, globals=None)
Now, let's see these concepts in action with a simple example of using timeit.
Sample Code:
import timeit
def simple_test():
my_list = []
n = 100
for i in range(n):
my_list.append(i)
print(timeit.timeit(stmt=simple_test))
Code Explanation: The simple_test() function appends n items to an array using a for loop that runs n times. Python’s timeit() function helps measure how long it takes to perform this task. Suppose you measure the execution time of the simple_test function and send this as a stmp argument in timeit.timeit function, which is a callable.
Output: This is the result you would obtain, which indicates the total time it took to execute simple_test.
2.9178604998160154
Let's see how the timeit function in Python works when timing a block of code.
Sometimes, you need to test code blocks rather than an entire function.
For this, you can use the other parameters and features of the timeit function in Python. There are two ways to execute multiple lines of code in timeit.timeit(). One approach is to separate the lines with semicolons, and the other is to enclose the code within triple quotes as a string.
The timeit() function accepts code as a single-line string, so to time multiple statements together, you can separate them using semicolons. The semicolon is helpful when you want to execute a series of steps, such as initializing a variable and performing a calculation, within a single timing block. It helps simulate a small, multi-step task without requiring a separate function, keeping the setup and stmt simple and within the same code string.
Sample Code: You're comparing the performance of a sum variable, setting x and y values in the setup, and using the variable a, which is initialized in the stmt.
import timeit
print(timeit.timeit(stmt="a=10; sum = x + y+a", setup="x = 10; y = 20", number=100000))
Output: The timeit function in Python returns a float, representing the total time (in seconds) it took to run the statement 100,000 times.
0.02587340999999999
The timeit function in Python expects code as a string. When your code spans multiple lines, writing it as a single-line string with semicolons can make it harder to read and maintain. In such cases, using triple quotes (""") allows you to write multi-line statements more clearly. This is especially useful when you need to time longer code blocks, such as loops, conditionals, or multi-step operations, where readability matters.
It works just like a multi-line string in Python. You can place multiple lines inside the stmt or setup parameters using triple quotes without breaking syntax.
Example: Let’s measure the time of only appending items to the array in the above code example.
import timeit
simple_test = """
for i in range(n):
my_list.append(i)
"""
setup = "n = 100; my_list=[1, 2, 3]"
global_variables = {'n': 0, 'my_list': []}
print(timeit.timeit(stmt=simple_test, setup=setup, number=10000,
globals=global_variables))
Code Explanation: You defined simple_test as the code block that appends items to a list, written as a multi-line string. You also used a setup string to handle initialization before the timing starts.
Next, you created a global_variables dictionary to include 'n' and 'my_list', so these can be accessed inside simple_test.
Variables like n and my_list used in the stmt must exist in the namespace where the string is executed. Usually, you’d pass them using the globals argument. In this case, you're preparing global variables = {'n': 0, 'my_list': [ ]} so that they can be accessed as global variables inside the stmt and setup strings.
You then passed each of these to their respective parameters—stmt, setup, and globals. You also set the number to 10,000 instead of the default 1,000,000, meaning the code block runs 10,000 times to calculate the total execution time.
Both stmt and setup can be either strings or callable objects. This example shows how to run multi-line code inside timeit.timeit() cleanly and effectively.
Output:
0.0021
Also Read: Top 30 Python Libraries for Data Science in 2024
Let’s explore different Python timeit() methods.
The timeit module in Python offers useful helper methods, such as timeit.default_timer() and timeit.repeat(), to enhance performance benchmarking and help identify bottlenecks in your code. default_timer() selects the most suitable clock on your system for high-precision timing. It is ideal when you need to time specific code blocks outside of the timeit manually.timeit() function.
repeat() runs the same code block multiple times and returns a list of execution times. It ensures that time measurements are accurate, even for fast code. This helps you avoid inaccurate results caused by temporary CPU load or background processes. Let’s take a closer look at two essential methods.
The default_timer() function returns the value (in fractional seconds) of a performance counter. It helps time the duration of a program or a specific code block. The timeit.default_timer() function selects the most precise clock based on your operating system, choosing the best timer available for Windows, Linux, or macOS. Here's how it works:
The clock choice depends on the operating system, ensuring you use the most accurate timer available for precise performance measurements. Here’s an example of how to use it:
Sample Code:
import timeit
start_time = timeit.default_timer()
# code to time
my_list = []
for i in range(100):
my_list.append(i)
end_time = timeit.default_timer()
total_time = end_time - start_time
print(total_time)
Code Explanation: In this example, you use default_timer() to record the start time and end time of a code block. Then, you subtract the start time from the end time to get the total execution time.
Output:
The start time is : 0.220261875
The time difference is : 0.0004737320000000045
Another helpful feature of the timeit module in Python is the repeat() function. This function works similarly to timeit(), but instead of running the code once, it runs it multiple times and returns a list of times. It is beneficial when you need to:
Here’s an example of how to use it:
Sample Code:
import timeit
# code to time
simple_test = """
my_list = []
for i in range(100):
my_list.append(i)
"""
print(timeit.repeat(simple_test, repeat=3))
Code Explanation: In this example, the repeat() function executes the simple test three times and prints a list of the results.
Output:
[2.752178000024287, 2.7493071000208147, 2.7419893000042066]
Now that you’ve learned about Python timeit methods, let’s compare them with other commonly used timing approaches to understand their advantages.
When benchmarking code in Python, you might wonder why you should use the timeit module when functions like time.time() and time.perf_counter() also return timestamps. While they all help measure time, their purposes, precision, and use cases differ significantly.
The timeit module is designed specifically for performance testing. It avoids common issues such as startup overhead, inconsistent results due to background tasks, or system load. On the other hand, built-in functions like time.time() or time.perf_counter() are general-purpose and not ideal for benchmarking small, fast code snippets.
Let’s compare these timing methods side-by-side in practical use cases:
Feature |
timeit (timeit module in Python) |
time.time() |
time.perf_counter() |
Purpose | Benchmark small code snippets accurately | Measure current time or total elapsed time | High-precision timer for short durations |
Precision | Very high, filter system noise | Low, depends on the system clock | High, including sleep time, and better resolution |
Repeatability | Yes, repeats code (default: 1,000,000 times) | No | No |
System Noise Handling | Ignores CPU load/background tasks by averaging | Sensitive to background processes | Less sensitive, but not immune |
Ease of Use | Needs stmt, setup, and number parameters | Very simple start-end timestamps | Simple, better precision than time.time() |
Best Use Case | Comparing different logics or implementations | Tracking full script runtime | Measuring short code blocks like DB/API calls |
When to Use | When optimizing and benchmarking code snippets | When logging runtime or timestamps | When you need precise time for a single execution |
Also Read: String Formatting in Python: 5 Comprehensive Techniques and Best Practices.
Let’s explore how to use timeit in Python directly from the Command Line Interface (CLI) for quick and efficient benchmarking.
While the timeit module in Python is commonly used within scripts, you can also run it directly from the Command Line Interface (CLI). This approach is ideal when you want to test small code snippets quickly without writing a full Python script. It’s handy for rapid benchmarking, quick comparisons, and iterative performance tuning.
You might prefer this method for its speed and convenience, particularly during development or experimentation. The syntax in the CLI differs slightly. To use timeit() in the command line, you don't need to import the timeit module like you would in a script. Instead, you use the python -m timeit command to run the timing function. Here’s the syntax and command line parameters:
python -m timeit [-n N] [-r N] [-u U] [-s S] [-p] [-v] [-h] [statement ...]
Command line parameters:
Sample Code 1: Let's say you want to test the performance of summing two numbers:
python -m timeit 'x = 10; y = 20; sum = x + y'
Code Explanation: The output displays the average execution time for this code snippet after running it multiple times (by default, 1,000,000 times).
Output:
10000000 loops, best of 5: 0.0235 usec per loop
Sample Code 2: You can also specify the number of executions using the -n flag, which is useful if you want to test how performance changes over a smaller number of iterations:
python -m timeit -n 1000 'x = 10; y = 20; sum = x + y'
Code Explanation: This will run the code 1,000 times instead of 1,000,000 times and give you the average execution time.
Output:
1000 loops, best of 5: 0.0235 usec per loop
Sample Code 3: This command measures the time it takes to sort a list of 10,000 random integers.
python -m timeit -s "import random; lst = [random.randint(0, 1000) for _ in range(10000)]" "sorted(lst)"
Code Explanation: The -s flag is for setup code that runs once before timing starts. Here, it imports the random module and creates a random list. "sorted(lst)" is the code being timed — it sorts the list. By default, timeit runs the test code multiple times (often 1,000,000) and reports the average time per execution.
Output:
100 loops, best of 5: 2.14 msec per loop
Now that we've covered the basics of Python's timeit() function, let's explore how it can be used as an effective profiling tool for optimizing your code's performance.
Profiling is the process of analyzing your program to understand where it spends most of its time and resources. It helps you pinpoint performance bottlenecks, such as inefficient loops, slow function calls, or memory-intensive operations. Profiling is typically done using tools like Python’s timeit for micro-benchmarking, cProfile for full-program profiling, and memory_profiler for monitoring memory usage.
These tools enable you to track and analyze the performance of different sections of your code, helping you make informed decisions, such as refactoring inefficient code or switching to faster libraries or methods for optimization.
While timeit in Python is not a comprehensive profiler like cProfile, it is ideal for microbenchmarking, which involves measuring the execution time of small, critical sections of your code. When profiling large applications, the timeit() function can be used to narrow down and analyze specific sections, such as individual functions, loops, or algorithm implementations that may be causing performance issues.
Here’s how timeit() works in real profiling scenarios:
Scenario: You're working on an application where you're adding elements to a list. You're unsure if using list.append() is slower than using the += operator for extending a list.
How timeit() helps: You can use timeit() to measure the execution time of both operations and identify which one is more efficient.
Example: This code snippet enables you to determine which method is faster and more efficient for your specific use case.
import timeit
append_time = timeit.timeit('lst.append(1)', setup='lst = []', number=1000000)
extend_time = timeit.timeit('lst += [1]', setup='lst = []', number=1000000)
print(f"Append time: {append_time}")
print(f"Extend time: {extend_time}")
Output:
Append time: 0.02563433814793825
Extend time: 0.10145936999469995
Scenario: When testing a function, you want to ensure your results are accurate despite external interference, such as background processes that may affect the performance test.
How timeit() helps: By running the code multiple times (default 1,000,000 iterations), timeit() averages out the noise from the operating system or any other background process running on your machine, offering consistent results.
Example: Running the code for a million iterations will smooth out any performance irregularities that occur due to background activities.
import timeit
setup = 'from math import sqrt'
stmt = 'sqrt(12345)'
execution_time = timeit.timeit(stmt, setup, number=1000000)
print(f"Execution time for sqrt: {execution_time}")
Output:
Execution time for sqrt: 0.272132
Also Read: Top 5 Python Modules You Should Know in 2024
Let's examine why python timeit() is considered one of the most effective methods for benchmarking Python code.
There are several ways to measure execution time; the timeit() function stands out for its accuracy, consistency, and streamlined integration into development workflows. Let's explore why timeit() is considered one of the best methods for measuring execution time in Python.
1. Accuracy and Reliability
2. Eliminates Background Noise
3. Customizable Setup and Execution
4. Ideal for Microbenchmarking
5. Quick and Easy to Use
Now that you’ve seen why timeit() is one of the most preferred tools for measuring execution time in Python, it’s equally important to understand the challenges that can arise while using it.
Also Read: Python Developer Salary in India in 2025 [For Freshers & Experienced]
While Python timeit() is an excellent tool for measuring performance, it presents some challenges in specific scenarios. Let's discuss these challenges.
Although timeit in Python is widely used for measuring execution time, it comes with a few challenges that can affect the accuracy and usability of the results. These challenges can lead to misleading benchmarks, unnecessary optimizations, or even incorrect conclusions about code performance.
For instance, external factors such as CPU load from other processes can introduce variability in timing results, thereby affecting accuracy. This makes it more challenging to determine whether performance improvements are genuine or merely the result of random fluctuations. You might assume the performance number reflects only your code, but it also includes background noise.
To maximize the accuracy of timeit(), it is essential to understand these pitfalls and know how to work around them. Let’s explore common challenges and practical solutions in the table below:
Challenge |
Impact on Performance Measurement |
How to Overcome It |
Example |
Improper Setup or Initialization | Variables not initialized properly may cause NameError or skew results due to the setup time included. | Use the setup parameter to initialize variables and imports separately. | setup="x=10; y=20" vs putting it in the stmt |
Not Accounting for System Noise | Background processes can cause fluctuations and inconsistent timings. | Use higher number values and timeit.repeat() to average out system noise. | repeat(stmt, repeat=3, number=100000) |
Too Simple Code Blocks | High-speed operations may result in near-zero timings, making it hard to compare. | Increase workload or add a loop inside the stmt to create a measurable execution time. | for _ in range(1000): 1+1 |
Unrealistic Benchmarks | Timing synthetic code might not reflect actual performance in production environments. | Simulate real inputs and test realistic logic flows. | Benchmark file reads using real or sample data |
Difficulty Testing Multi-line Code | Writing multi-line logic in a single string can be difficult to manage. | Use triple quotes (''') or define' stmt' and' setup' as callable functions. | stmt='''for i in range(10): total += i''' |
Use the Python timeit() function to test various code implementations, such as loops, functions, and conditional statements, and identify areas that require optimization. Practice benchmarking different sections of your code, and experiment with performance tweaks to see real improvements. As you refine your code’s performance, you'll create more efficient, scalable applications that run seamlessly in real-world scenarios.
If you’re looking to sharpen your Python performance skills or build a stronger coding foundation, upGrad’s structured courses can help you apply concepts with real-world confidence. With a portfolio of over 200 courses and partnerships with more than 1,400 hiring companies, upGrad provides a learning experience tailored to your career growth.
Here are some of the top courses from upGrad designed to enhance your knowledge:
Book a free career counseling session today for personalized guidance from industry experts, or visit your nearest upGrad career centre to start accelerating your future!
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources