---
description: timeit() method is available with python library timeit. It is used to get the execution time taken for the small code given. The library runs the code statement 1 million times and provides the minim
title: Python Timeit() with Examples
image: https://www.guru99.com/images/python-timeit.png
---

 

[Skip to content](#main) 

**⚡ Smart Summary**

Python Timeit() measures the execution time of a small code snippet by running it many times and returning the minimum duration. It supports the timeit, repeat, and default\_timer methods and works from scripts or the command line.

* ⏱️ **Timeit Defined:** Measures execution time of a code snippet, returning the minimum over many runs.
* 🧩 **Parameters:** stmt, setup, timer, and number control what runs and how often.
* 🔁 **Methods:** timeit(), repeat(), and default\_timer() offer different timing options.
* 💻 **Command Line:** Run python -m timeit with flags like -n, -r, and -s.
* ✅ **Why Use It:** Disables garbage collection and picks the most accurate timer per operating system.

[ Read More ](javascript:void%280%29;) 

![Python Timeit\(\)](https://www.guru99.com/images/python-timeit.png)

## What is Python Timeit()?

**Python timeit()** is a method in Python library to measure the execution time taken by the given code snippet. The Python library runs the code statement 1 million times and provides the minimum time taken from the given set of code snippets. Python timeit() is a useful method that helps in checking the performance of the code.

## Syntax

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

### Parameters

* **stmt**: This will take the code for which you want to measure the execution time. The default value is “pass”.
* **setup**: This will have setup details that need to be executed before stmt. The default value is “pass.”
* **timer**: This will have the timer value, timeit() already has a default value set, and we can ignore it.
* **number**: The stmt will execute as per the number is given here. The default value is 1000000.

To work with timeit(), we need to import the module, as shown below:

import timeit

## First Example

Here is a simple example of timeit() function

### Code Example 1

# testing timeit()
import timeit
print(timeit.timeit('output = 10*5'))

****Output:**

0.06127880399999999

We have seen a simple example that gives us the execution time of the simple code statement output = 10\*5, and the time is taken to execute it is 0.06127880399999999.

## Timing Multiple lines in python code

There are two ways to execute multiple lines of code in timeit.timeit(): by separating the lines with semicolons or enclosing the code as a string with triple quotes.

Here are examples that show the working of it.

### Example 1: Using semicolon

import timeit
print("The time taken is ",timeit.timeit(stmt='a=10;b=10;sum=a+b'))

**Output:**

The time taken is  0.137031482

### Example 2: Using triple quotes

import timeit
import_module = "import random"
testcode = '''
def test():
    return random.randint(10, 100)
'''
print(timeit.repeat(stmt=testcode, setup=import_module))

**Output:**

C:\pythontest>python testtimeit.py
The time taken is  0.182619178

### RELATED ARTICLES

* [Python XML File – How to Read, Write & Parse ](https://www.guru99.com/manipulating-xml-with-python.html "Python XML File – How to Read, Write & Parse")
* [Python Lambda Functions with EXAMPLES ](https://www.guru99.com/python-lambda-function.html "Python Lambda Functions with EXAMPLES")
* [Python Counter in Collections with Example ](https://www.guru99.com/python-counter-collections-example.html "Python Counter in Collections with Example")
* [Yield in Python Tutorial: Generator & Yield vs Return Example ](https://www.guru99.com/python-yield-return-generator.html "Yield in Python Tutorial: Generator & Yield vs Return Example")

## timeit – Methods

Here, are 2 important timeit methods

**timeit.default\_timer()** : This will return the default time when executed.

**timeit.repeat(stmt, setup, timer, repeat, number)** : same as timeit() , but with repeat the timeit() is called the number of times repeat is given.

### Program Example 1

# testing timeit()
import timeit
import_module = "import random"
testcode = '''
def test():
    return random.randint(10, 100)
'''
print(timeit.timeit(stmt=testcode, setup=import_module))

**Output:**

0.46715912400000004

### Example 2

default\_timer() Example

# testing timeit()

import timeit
import random

def test():
    return random.randint(10, 100)

starttime = timeit.default_timer()
print("The start time is :",starttime)
test()
print("The time difference is :", timeit.default_timer() - starttime)

**Output:**

The start time is : 0.220261875
The time difference is : 0.0004737320000000045

### Example 3: timeit.repeat()

# testing timeit()
import timeit
import_module = "import random"
testcode = '''
def test():
    return random.randint(10, 100)
'''
print(timeit.repeat(stmt=testcode, setup=import_module, repeat=5))

**Output:**

 [0.43638873, 0.5040939680000001, 0.5069179909999999, 0.3943449330000002, 0.3546886979999999]

timeit.repeat() works similar to timeit.timeit() function, with the only difference it takes in the repeat argument and gives back the execution time in array format with values as per the repeat number.

## Executing timing function timeit.timeit() inside command-line interface

The syntax to execute your function inside timeit() on the command line is as follows:

python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [code 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 have setup details that will get 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.

### Example

C:\pythontest>python -m timeit -s 'text="hello world"'
20000000 loops, best of 5: 13.1 nsec per loop

Another way you can execute inside command line is as shown below:

### Example

>>> import timeit
>>> print("The time taken is ",timeit.timeit(stmt='a=10;b=10;sum=a+b'))
The time taken is  0.15048536300000137
>>>

## Why is timeit() the best way to measure the execution time of Python code?

Here are a few reasons why we consider timeit() is the best way to measure execution time.

* It runs the code statement 1 million times that is the default value, and from that, it will return you the minimum time taken. You can also increase/decrease the 1 million by setting the argument number in time () function.
* While executing the test, the garbage collection is disabled every time by time () function.
* timeit() internally takes the accurate time as per your operating system being used. For example, it will use time.clock() for Windows operating system and time.time() for mac and Linux.

## FAQs

⚖️ What is the difference between timeit.timeit() and timeit.repeat()?

timeit.timeit() runs the statement a set number of times and returns a single total time. timeit.repeat() runs that whole measurement several times and returns a list of results, letting you pick the best.

🗑️ Why does timeit disable garbage collection?

timeit disables garbage collection during measurement so background cleanup does not distort the timing. This makes results more consistent and comparable, focusing purely on the execution time of the snippet being tested.

📑 How do you time multiple lines of code with timeit?

You can separate statements with semicolons inside the stmt string, or pass a multi-line string using triple quotes. For functions, define them in setup and call them from stmt.

🤖 How can AI help optimize slow Python code?

AI can profile code, identify slow loops or expensive calls, suggest vectorized or built-in alternatives, and recommend better data structures, helping developers focus optimization where timeit shows the biggest bottlenecks.

🧠 Can AI suggest faster alternatives to a timed snippet?

Yes. Given a snippet and its timeit results, AI can propose rewrites such as list comprehensions, generator expressions, or library functions, then you re-run timeit to confirm the improvement is real.

#### Summarize this post with:

ChatGPT Perplexity Grok Google AI 

**Stay Updated on AI** **Get Weekly AI Skills, Trends, Actionable Advice.** 

##### Sign up for the newsletter

Subscribe for Free 

You have successfully subscribed.  
Please check your inbox. 

![AI-Newsletter]() Chosen by over **350,000+** professionals 

[Scroll to top ](#wrapper)Scroll to top 

× 

Toggle Menu Close 

Search for: 

Search

```json
{"@context":"https://schema.org","@graph":[{"@type":"Organization","@id":"https://www.guru99.com/#organization","name":"Guru99","sameAs":["https://www.facebook.com/Guru99Official","https://twitter.com/guru99com"],"logo":{"@type":"ImageObject","@id":"https://www.guru99.com/#logo","url":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","contentUrl":"https://www.guru99.com/images/guru99-logo-v1-150x59.png","caption":"Guru99","inLanguage":"en-US"}},{"@type":"WebSite","@id":"https://www.guru99.com/#website","url":"https://www.guru99.com","name":"Guru99","publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US"},{"@type":"ImageObject","@id":"https://www.guru99.com/images/python-timeit.png","url":"https://www.guru99.com/images/python-timeit.png","width":"700","height":"250","caption":"Python Timeit()","inLanguage":"en-US"},{"@type":"BreadcrumbList","@id":"https://www.guru99.com/timeit-python-examples.html#breadcrumb","itemListElement":[{"@type":"ListItem","position":"1","item":{"@id":"https://www.guru99.com","name":"Home"}},{"@type":"ListItem","position":"2","item":{"@id":"https://www.guru99.com/python","name":"Python"}},{"@type":"ListItem","position":"3","item":{"@id":"https://www.guru99.com/timeit-python-examples.html","name":"Python Timeit() with Examples"}}]},{"@type":"WebPage","@id":"https://www.guru99.com/timeit-python-examples.html#webpage","url":"https://www.guru99.com/timeit-python-examples.html","name":"Python Timeit() with Examples","dateModified":"2026-06-30T17:33:45+05:30","isPartOf":{"@id":"https://www.guru99.com/#website"},"primaryImageOfPage":{"@id":"https://www.guru99.com/images/python-timeit.png"},"inLanguage":"en-US","breadcrumb":{"@id":"https://www.guru99.com/timeit-python-examples.html#breadcrumb"}},{"@type":"Person","@id":"https://www.guru99.com/author/logan","name":"Logan Young","description":"I'm Logan Young, an expert in Python, providing top-tier tutorials and guides to enhance your coding skills and streamline your learning journey.","url":"https://www.guru99.com/author/logan","image":{"@type":"ImageObject","@id":"https://www.guru99.com/images/logan-young-author.png","url":"https://www.guru99.com/images/logan-young-author.png","caption":"Logan Young","inLanguage":"en-US"},"worksFor":{"@id":"https://www.guru99.com/#organization"}},{"articleSection":"Python","headline":"Python Timeit() with Examples","description":"timeit() method is available with python library timeit. It is used to get the execution time taken for the small code given. The library runs the code statement 1 million times and provides the minim","keywords":"python","speakable":{"@type":"SpeakableSpecification","cssSelector":[".entry-title",".summary"]},"@type":"Article","author":{"@id":"https://www.guru99.com/author/logan","name":"Logan Young"},"dateModified":"2026-06-30T17:33:45+05:30","image":{"@id":"https://www.guru99.com/images/python-timeit.png"},"copyrightYear":"2026","name":"Python Timeit() with Examples","subjectOf":[{"@type":"FAQPage","mainEntity":[{"@type":"Question","name":"What is the difference between timeit.timeit() and timeit.repeat()?","acceptedAnswer":{"@type":"Answer","text":"timeit.timeit() runs the statement a set number of times and returns a single total time. timeit.repeat() runs that whole measurement several times and returns a list of results, letting you pick the best."}},{"@type":"Question","name":"Why does timeit disable garbage collection?","acceptedAnswer":{"@type":"Answer","text":"timeit disables garbage collection during measurement so background cleanup does not distort the timing. This makes results more consistent and comparable, focusing purely on the execution time of the snippet being tested."}},{"@type":"Question","name":"How do you time multiple lines of code with timeit?","acceptedAnswer":{"@type":"Answer","text":"You can separate statements with semicolons inside the stmt string, or pass a multi-line string using triple quotes. For functions, define them in setup and call them from stmt."}},{"@type":"Question","name":"How can AI help optimize slow Python code?","acceptedAnswer":{"@type":"Answer","text":"AI can profile code, identify slow loops or expensive calls, suggest vectorized or built-in alternatives, and recommend better data structures, helping developers focus optimization where timeit shows the biggest bottlenecks."}},{"@type":"Question","name":"Can AI suggest faster alternatives to a timed snippet?","acceptedAnswer":{"@type":"Answer","text":"Yes. Given a snippet and its timeit results, AI can propose rewrites such as list comprehensions, generator expressions, or library functions, then you re-run timeit to confirm the improvement is real."}}]}],"@id":"https://www.guru99.com/timeit-python-examples.html#schema-1126961","isPartOf":{"@id":"https://www.guru99.com/timeit-python-examples.html#webpage"},"publisher":{"@id":"https://www.guru99.com/#organization"},"inLanguage":"en-US","mainEntityOfPage":{"@id":"https://www.guru99.com/timeit-python-examples.html#webpage"}}]}
```
