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
timeit module is part of the Python standard library, and you can import it:
The syntax to use the
timeit function from the
timeit module is as shown below:
timeit.timeit(stmt, setup, number)
stmtis 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,
setupdenotes the piece of code that needs to run only once, often as a prerequisite for the
stmtto run. For example, suppose you’re computing the execution time for the creation of a NumPy array. In this case, importing
setupcode and the actual creation is the statement to to be timed.
- The parameter
numberdenotes the number of times the
stmtis run. The default value of
numberis 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) 0.0004020999999738706 >>> timeit.timeit('3**4;3//4',number=100000) 0.0013780000000451764
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 timeitrepresents that we run
timeitas the main module.
nis a command-line option that denotes the number of times the code should run. This is equivalent to the
numberargument in the
- You can use the option
-sto 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
$ 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
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
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
string_1[1:4] returns ‘yth’.
>>> string_1 = 'Python' >>> string_1[1:4] 'yth'
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.
stop value is 3, so the slice starts at index 0 and goes up to index 2.
>>> string_1[:3] 'Pyt'
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:] 'ython'
Ignoring both the
start and the
stop values returns a slice of the entire string.
>>> string_1[::] 'Python'
Let’s create a slice with the
step value. Set the
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] 'yh'
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] 'nh'
So to get a reversed copy of the string, we skip the
stop values and set the step to -1, as shown:
>>> string_1[::-1] 'nohtyP'
string[::-1]returns a reversed copy of the string.
Reversing Strings Using Built-In Functions and String Methods
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): print(char)
And access the elements of the string in the reverse order.
# Output n o h t y P
Next, you can then call the
join() method on the reverse iterator with the syntax:
The code snippet below shows a couple of examples where the separator is a hyphen and a whitespace, respectively.
>>> '-'.join(reversed(string1)) 'n-o-h-t-y-P' >>> ' '.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)) 'nohtyP'
''.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
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) 0.04951830000001678 >>> timeit.timeit(stmt = "''.join(reversed(string_1))", setup = "string_1 = 'Python'", number = 100000) 0.12858760000000302
For the same number of runs for reversing the given string, the string slicing approach is faster than using the
join() method and
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): str_with_digit.append(string) return str_with_digit
Now we would like to measure the execution time of this Python function
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
- 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): str_with_digit.append(string) return str_with_digit thislist=['puffin3','7frost','blue'] """
Next, we can use the
timeit function and get the execution time of the
hasDigit() function for 100000 runs.
import timeit timeit.timeit('hasDigit(thislist)',setup=setup,number=100000)
# Output 0.2810094920000097
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.