Calculate Python Code Execution Elapsed Time with Timer – Python Tutorial

By | September 20, 2023

In order to get the elapsed time of a python code we are running, we can use time or datetime. Here is the tutorial:

Calculate the Execution Time of a Python Program – A Step Guide – Python Tutorial

However, the time and datetime is not easy to use. In this tutorial, we will introduce a simpler way to get this elapsed time, the timer package will be used.

Install python timer package

We can use pip to install.

pip install -i https://mirrors.aliyun.com/pypi/simple/ timer --trusted-host mirrors.aliyun.com

Get the elapsed time of a python code

We can use with timer() as t to get the elapsed time easily.

For examle:

from timer import timer
import time

def run():
    print(3)
    time.sleep(1)
    print(f'after time.sleep(1) once, t.elapse = {t.elapse}')
    time.sleep(1)
    print(f'after time.sleep(1) twice, t.elapse = {t.elapse}')
if __name__ == '__main__':
    # 'timer' would be timer's name by default
    with timer() as t:
        run()
    print(f'after with, t.elapse = {t.elapse}')

Run this code, we will see:

3
after time.sleep(1) once, t.elapse = 1.0183972
after time.sleep(1) twice, t.elapse = 2.0384254
after with, t.elapse = 2.0384640000000003

In this example, we will calculate the elapsed time of python function run(). t.elapse is what we want to compute.

Compared with time and datetime, it is much easier to do.