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 npdef 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 secondsresult.worst: the worst execution time in secondsresult.average: the average execution time in secondsresult.stdev: the standard deviation of the execution times in secondsresult.all_runs: a list of all the execution times in secondsFor 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.