In Development Last updated:
Share on:
Cloudways offers managed cloud hosting for any size business to host a website or complex web applications.

In this tutorial, you’ll learn how to use the timeit function from Python’s timeit module. You’ll learn how to time simple expressions and functions in Python.

Timing your code can help you get an estimate of the execution time of a piece of code and also identify the sections of the code that need to be optimized.

We’ll start by learning the syntax of Python’s timeit function. And then we’ll code examples to understand how to use it to time blocks of code and functions in your Python module. Let’s begin.

How to Use the Python timeit Function

The timeit module is part of the Python standard library, and you can import it:

import timeit

The syntax to use the timeit function from the timeit module is as shown below:

timeit.timeit(stmt, setup, number)


  • stmt is the piece of code whose execution time is to be measured. You can specify it as a simple Python string or a multiline string, or pass in the name of the callable.
  • As the name suggests, setup denotes the piece of code that needs to run only once, often as a prerequisite for the stmt to run. For example, suppose you’re computing the execution time for the creation of a NumPy array. In this case, importing numpy is the setup code and the actual creation is the statement to to be timed.
  • The parameter number denotes the number of times the stmt is run. The default value of number is 1 million (1000000), but you can also set this parameter to any other value of your choice.

Now that we’ve learned the syntax to use the timeit() function, let’s start coding some examples.

Timing Simple Python Expressions

In this section, we’ll try to measure the execution time of simple Python expressions using timeit.

Start a Python REPL and run the following code examples. Here, we’re computing the execution time of exponentiation and floor division operations for 10000 and 100000 runs.

Notice that we pass in the statement to be timed as a Python string and use a semicolon to separate the different expressions in the statement.

>>> import timeit
>>> timeit.timeit('3**4;3//4',number=10000)

>>> timeit.timeit('3**4;3//4',number=100000)

Running Python timeit at the Command Line

You can also use timeit at the command line. Here is the command-line equivalent of the timeit function call:

$ python-m timeit -n [number] -s [setup] [stmt]
  • python -m timeit represents that we run timeit as the main module.
  • n is a command-line option that denotes the number of times the code should run. This is equivalent to the number argument in the timeit() function call.
  • You can use the option -s to define the setup code.

Here, we rewrite the previous example using the command-line equivalent:

$ python -m timeit -n 100000 '3**4;3//4'
100000 loops, best of 5: 35.8 nsec per loop

In this example, we compute the execution time of the built-in len() function. The initialization of the string is the setup code that’s passed in using the s option.

$ python -m timeit -n 100000 -s "string_1 = 'coding'" 'len(string_1)'
100000 loops, best of 5: 239 nsec per loop

In the output, notice that we get the execution time for best of 5 runs. What does this mean? When you run timeit at the command line, the repeat option r is set to the default value of 5. This means the execution of the stmt for the specified number of times is repeated five times, and the best of the execution times is returned.

Analysis of String Reversal Methods Using timeit

When working with Python strings, you may want to reverse them. The two most common approaches to string reversal are as follows:

  • Using string slicing
  • Using the reversed() function and the join() method

Reverse Python Strings Using String Slicing

Let’s go over how string slicing works, and how you can use it to reverse a Python string. Using the syntax some-string[start:stop] returns a slice of the string starting at the index start and extending up to the index stop-1. Let’s take an example.

Consider the following string ‘Python’. The string is of length 6 and the list of indices is 0, 1, 2 up to 5.

>>> string_1 = 'Python'

When you specify both the start and the stop values, you get a string slice that extends from start to stop-1. Therefore, string_1[1:4] returns ‘yth’.

>>> string_1 = 'Python'
>>> string_1[1:4]

When you do not specify the start value, the default start value of zero is used, and the slice starts at index zero and extends up to stop - 1.

Here, the stop value is 3, so the slice starts at index 0 and goes up to index 2.

>>> string_1[:3]

When you do not include the stop index, you see that the slice starts from the start index (1) and extends up to the end of the string.

>>> string_1[1:]

Ignoring both the start and the stop values returns a slice of the entire string.

>>> string_1[::]

Let’s create a slice with the step value. Set the start, stop, and step values to 1, 5, and 2, respectively. We get a slice of the string starting at 1 extending up to 4 (excluding the end point 5) containing every second character.

>>> string_1[1:5:2]

When you use a negative step, you can get a slice starting at the end of the string. With the step set to -2, string_1[5:2:-2] gives the following slice:

>>> string_1[5:2:-2]

So to get a reversed copy of the string, we skip the start and stop values and set the step to -1, as shown:

>>> string_1[::-1]

In summary: string[::-1] returns a reversed copy of the string.

Reversing Strings Using Built-In Functions and String Methods

The built-in reversed() function in Python will return a reverse iterator over the elements of the string.

>>> string_1 = 'Python'
>>> reversed(string_1)
<reversed object at 0x00BEAF70>

So you can loop through the reverse iterator using a for loop:

for char in reversed(string_1):

And access the elements of the string in the reverse order.

# Output

Next, you can then call the join() method on the reverse iterator with the syntax: <sep>.join(reversed(some-string)).

The code snippet below shows a couple of examples where the separator is a hyphen and a whitespace, respectively.

>>> '-'.join(reversed(string1))
>>> ' '.join(reversed(string1))
'n o h t y P'

Here, we do not want any separator; so set the separator to an empty string to get a reversed copy of the string:

>>> ''.join(reversed(string1))

Using ''.join(reversed(some-string)) returns a reversed copy of the string.

Comparing Execution Times Using timeit

So far, we have learned two approaches to reverse Python strings. But which of them is faster? Let’s find out.

In a previous example where we timed simple Python expressions, we did not have any setup code. Here, we are reversing the Python string. While the string reversal operation runs for the number of times specified by number, the setup code is the initialization of the string that’ll run only once.

>>> import timeit
>>> timeit.timeit(stmt = 'string_1[::-1]', setup = "string_1 = 'Python'", number = 100000)
>>> timeit.timeit(stmt = "''.join(reversed(string_1))", setup = "string_1 = 'Python'", number = 100000)

For the same number of runs for reversing the given string, the string slicing approach is faster than using the join() method and reversed() function.

You may also read how to reverse a list in Python to spin it backwards.

Timing Python Functions Using timeit

In this section, let’s learn how to time Python functions with the timeit function. Given a list of strings, the following function hasDigit returns the list of strings that have at least one digit.

def hasDigit(somelist):
     str_with_digit = []
     for string in somelist:
         check_char = [char.isdigit() for char in string]
         if any(check_char):
     return str_with_digit

Now we would like to measure the execution time of this Python function hasDigit() using timeit.

Let’s first identify the statement to be timed (stmt). It is the call to the function hasDigit() with a list of strings as the argument. Next, let’s define the setup code. Can you guess what the setup code should be?

For the function call to run successfully, the setup code should include the following:

  • The definition of the function hasDigit()
  • The initialization of the argument list of strings

Let’s define the setup code in the setup string, as shown below:

setup = """
def hasDigit(somelist):
    str_with_digit = []
    for string in somelist:
      check_char = [char.isdigit() for char in string]
      if any(check_char):
    return str_with_digit

Next, we can use the timeit function and get the execution time of the hasDigit() function for 100000 runs.

import timeit
# Output


You’ve learned how to use Python’s timeit function to time expressions, functions, and other callables. This can help you benchmark your code, compare the execution times of different implementations of the same function, and more.

Let’s review what we have learned in this tutorial. You can use the timeit() function with the syntax timeit.timeit(stmt=...,setup=...,number=...). Alternatively, you can run timeit at the command line to time short code snippets.

As a next step, you can explore how to use other Python profiling packages like line-profiler and memprofiler to profile your code for time and memory, respectively.

Next, learn how to calculate time difference in Python.

Share on:
  • Bala Priya C
    Bala Priya is a developer and technical writer from India with over three years of experience in the technical content writing space. She shares her learning with the developer community by authoring tech tutorials, how-to guides, and more….

Thanks to our Sponsors

More great readings on Development

Power Your Business

Some of the tools and services to help your business grow.
  • The text-to-speech tool that uses AI to generate realistic human-like voices.

    Try Murf AI
  • Web scraping, residential proxy, proxy manager, web unlocker, search engine crawler, and all you need to collect web data.

    Try Brightdata
  • is an all-in-one work OS to help you manage projects, tasks, work, sales, CRM, operations, workflows, and more.

    Try Monday
  • Intruder is an online vulnerability scanner that finds cyber security weaknesses in your infrastructure, to avoid costly data breaches.

    Try Intruder