Time Related Tips

Learn how to write time-efficient Python code.

Time it

A popular saying among programmers is “Make it right, then make it fast.” Assuming that our program is correct and that we have several solutions, we want the fastest option. This is often the case in Python, despite the principle from The Zen of Python that says: “There should be one—and preferably only one— obvious way to do it.”

An incorrect way to time our code is to call the time() function from the namesake module before and after the code fragment of interest. The accuracy of the function is low, usually well below the fragment execution time. The right tool for the job is the function, timeit(),in the timeit module. The function takes some parameters, the first two being the most important.

  • The first parameter is the code fragment that we want to time. We must provide it to the function as a string. Otherwise, Python will execute it before calling the timing function. The code must include the definitions of all involved variables because the function evaluates the parameters in a clean environment that doesn’t include any previously defined functions and variables or previously imported modules. The function evaluates the code number times, where the number is an optional parameter, and returns the average execution time.
  • The second parameter is another string that contains the initialization code. The timeit() function executes this code once before it starts collecting statistics. We can use this parameter to import modules or define global variables.

We may wonder what the best way to square a number is. Do we multiply it by itself, use the exponential operator (**), or call math.pow()?In cases like this, we should turn to The Zen of Python, which says “In the face of ambiguity, refuse the temptation to guess." Use the Timeit()!

Note: If we apply the first two code fragments to an integer, the results will be quite different. For more details, see the Beware of Large and Slow Ints section at the end of this lesson. The function returns the total execution time in seconds.

The Timeit() function executes the statement number=1,000,000 times. Divide the returned time by number to get the time-per-statement execution.

Let’s run the below code.

Press + to interact
print(timeit.timeit('a ** 2', 'a = 10.0'))
print(timeit.timeit('a * a', 'a = 10.0'))
print(timeit.timeit('math.pow(a, 2)', 'import math; a = 10.0'))

While having all seventeen digits after ...