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: The syntax to use the timeit function from the timeit module is as shown below: Here:
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.
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 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: 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. 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. 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’. 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. 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. Ignoring both the start and the stop values returns a slice of the entire string. 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. 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: So to get a reversed copy of the string, we skip the start and stop values and set the step to -1, as shown:
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.
So you can loop through the reverse iterator using a for loop:
And access the elements of the string in the reverse order.
Next, you can then call the join() method on the reverse iterator with the syntax:
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. 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.
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. 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: Next, we can use the timeit function and get the execution time of the hasDigit() function for 100000 runs.
Conclusion
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.