View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All
View All

Python timeit(): How to Time Your Code (2025)

By Rohit Sharma

Updated on Apr 24, 2025 | 20 min read | 1.5k views

Share:

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.

What is Python Timeit()?

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:

  • String Concatenation: Should you use "".join() or repeated += operations in a loop? timeit can give a definitive answer.
  • Data Structure Choices: Should You Choose a List, Set, or Dictionary for Lookups? timeit helps benchmark lookup times to inform your decision.
  • Algorithm Tweaks: Comparing the performance of a recursive vs. an iterative solution for a problem? Timeit reveals the real-world cost.

Looking to optimize your Python code and master performance tuning? Enroll in online software development courses to acquire essential skills, including efficient coding practices and performance optimization.

Understanding the Syntax

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)
  • stmt: The statement you want to measure, which should be callable or a string, and the default is ‘pass’.
  • setup: Setup details that must be executed before the statement, such as initializing variables and importing necessary modules. This should be callable or a string, with the default being ‘pass’.
  • timer: timer.Timer object, we can ignore this
  • number: The number of times the stmt will be executed, and the default is 1,000,000.
  • globals: A dictionary containing global variables for stmt and setup, and the default is 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.

Timing Multiple Lines In Python 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.

1. Using Semicolon

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

2. Using Triple Quotes

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
background

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

Master performance-aware coding with real-world data workflows. upGrad’s Data Science program teaches you to write optimized, scalable code for data processing and analysis.

Also Read: Top 30 Python Libraries for Data Science in 2024

Let’s explore different Python timeit() methods.

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.

1. timeit.default_timer()

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:

  • On Unix-based systems, such as Linux and macOS, it uses time.perf_counter(), which provides the highest available resolution clock, measures time with the greatest precision.
  • On Windows, it uses time.clock(), although this was deprecated in Python 3.8 and replaced with time.perf_counter(), which is designed to give accurate time measurements as well.

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

2. timeit.repeat()

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:

  • Check performance consistency: It provides a range of execution times, helping you determine if the code performs consistently or if system factors such as CPU load, background processes, or memory usage are influencing the results.
  • Compare multiple implementations: You can use it to compare different ways of solving a problem (e.g., two sorting algorithms) and choose the most efficient one based on repeated performance measurements.
  • Identify performance bottlenecks: By running the code multiple times, you can spot slowdowns or outliers in performance, which helps you identify specific areas of your code that may require optimization.
  • Make informed decisions: Repeated runs give you a more reliable average, reducing the impact of system fluctuations. This enables more accurate comparisons and improved optimizations.

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]

Interested in taking your Python skills to the next level? This Executive Diploma in Machine Learning and AI with Python helps you master advanced concepts like Deep Learning, NLP, and MLOps, equipping you to build optimized and scalable AI solutions.

Now that you’ve learned about Python timeit methods, let’s compare them with other commonly used timing approaches to understand their advantages.

Comparison with Other Timing Methods

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.

Executing Timing Function time.timieit() Inside Command Line Interface

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:

  • -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 contain setup details that will be 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.

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

Kickstart your Python journey with upGrad’s free Basic Python Programming course. Learn fundamentals, real-world applications & hands-on exercises in 12 hours of learning and earn a certificate today!

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.

Python timeit() as a Profiling Tool

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.

How timeit() Helps in Profiling

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:

1. Pinpointing Slow Code Paths

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

2. Accurate & Consistent Results

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.

Why is timeit() the Best Way to measure the Execution Time of 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

  • timeit() runs code multiple times (default: 1,000,000) to get more reliable results. This reduces the impact of external factors, such as OS processes or background tasks, providing more accurate benchmarking.
  • Example: Measuring simple arithmetic operations, such as x + y, can fluctuate if executed only once due to system processes. With timeit(), you get a stable, averaged result.

2. Eliminates Background Noise

  • Unlike other methods, such as time.time(), which can be affected by background tasks and other system events, timeit() minimizes interference by running the code repeatedly in a clean environment.
  • Example: If you are testing a sorting function, timeit() helps ensure that your test results are not skewed by unrelated system activity.

3. Customizable Setup and Execution

  • timeit() allows you to customize the number of iterations (number) and the setup process (through the setup parameter), giving you flexibility in testing real-world scenarios.
  • Example: You can test the performance of appending elements to a list (list.append()) vs concatenating lists using the + operator, and specify the setup to initialize the lists with specific data.

4. Ideal for Microbenchmarking

  • timeit() is optimized for testing small sections of code, such as individual functions or algorithm implementations. This makes it ideal for microbenchmarking, where you want to focus on performance down to the most minor details.
  • Example: You can compare the execution time of different sorting algorithms (e.g., sorted() vs. sort()) using timeit() to choose the more efficient one for your use case.

5. Quick and Easy to Use

  • timeit() can be executed directly in the command line or within a script, making it quick and easy to use without requiring complex setup code. This makes it convenient for developers who want to quickly test and compare code performance without having to create a complete test suite.
  • Example: Instead of creating a complete script to measure execution time, you can run python -m timeit 'your_code_here' directly in the terminal, saving you time on setup.

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.

Challenges of Using Python Timeit() and How to Overcome Them?

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'''

How Can upGrad Help You Learn Python Programming?

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!

Frequently Asked Questions

1. How does the timeit() function differ from using time.time() to measure execution time?

2. Can I use timeit() to benchmark functions that require complex setup, like reading from files or using external APIs?

3. What’s the best way to benchmark multi-line code with timeit()? I always run into syntax issues.

4. I’m trying to compare a list comprehension to a for-loop. How can timeit() help me make an informed choice?

5. What if I need to use a global variable in my timed code? Will timeit() still work?

6. Is timeit() useful for larger scripts or just for small code snippets?

7. Why do I get inconsistent results when timing fast operations like simple math?

8. How does timeit() deal with system-level noise like CPU scheduling or background processes?

9. I’m using timeit() in Jupyter Notebook and getting weird results. Why?

10. Is there a performance limit where timeit() is no longer the right tool to use?

11. Can I pass functions with arguments to timeit()? I’m not sure how to include inputs.

Rohit Sharma

752 articles published

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Dual Credentials

Master's Degree

17 Months

IIIT Bangalore logo
bestseller

The International Institute of Information Technology, Bangalore

Executive Diploma in Data Science & AI

Placement Assistance

Executive PG Program

12 Months