2 Ways to Measure the Code Execution Time in Google Colab
( 48 Articles)
This short and straight-to-the-point article shows you two different ways to measure the execution time of a piece of Python code in Google Colab.
Using %timeit
The %timeit magic function (function with a prefix is a percent symbol %) is useful for timing code with very short execution time. It runs a statement multiple times to calculate an ensemble average execution time. You may get results in µs (microsecond) or ns (nanosecond).
Example:
import numpy as np
x = np.random.rand(100, 100)
%timeit np.matmul(x, x)
Output:
The slowest run took 38.18 times longer than the fastest. This could mean that an intermediate result is being cached.
10000 loops, best of 5: 126 µs per loop
Screenshot:

Using autotime extension
This approach is convenient if you want to see the execution time of every cell in a Google Colab notebook.
1. Installing ipython-autotime:
!pip install ipython-autotime
2. Loading the autotime extension (you only need to do this once):
%load_ext autotime
Example:

Conclusion
We’ve gone through a couple of different methods to benchmark the execution time of a piece of code or a cell in Google Colab. If you’d like to explore more about Python programming, take a look at the following articles:
- How to Install Python Libraries in Google Colab
- Python zip() function examples
- Python reduce() function examples
- Python filter() function examples
- VS Code: How to comment out a block of Python code
You can also check out our Machine Learning category page or Python category page for more tutorials and examples.