In Jupyter notebooks, we can save the output of %timeit to a variable using the -o option. This is useful if we want to analyze the timing results or compare different implementations of a function.

Here's an example:

import numpy as np
 
def my_function():
    x = np.random.rand(10000)
    y = np.random.rand(10000)
    return x.dot(y)
 
result = %timeit -o my_function()

This will run my_function() several times and store the timing results in the result variable. We can then access the timing information using the following attributes:

  • result.best: the best execution time in seconds
  • result.worst: the worst execution time in seconds
  • result.average: the average execution time in seconds
  • result.stdev: the standard deviation of the execution times in seconds
  • result.all_runs: a list of all the execution times in seconds

For example, to print the best execution time, we can use:

print(result.best)

This will print the best execution time in seconds.

By saving the output of %timeit to a variable and analyzing the results, we can get a better understanding of the performance characteristics of our code and identify areas for improvement.