Writing Decorator Functions to Time Your Python Code

Liu Zuo Lin
4 min readNov 6, 2021

Sometimes we have to write code that takes a while to run, be it a web-scraping task, a data preprocessing task or whatnot. In these cases, we probably want to use some sort of timer function to check how long our blocks of code takes to run.

The Simplest Way To Time Your Code

Here’s the simplest but manual way to time your code:

from time import timestart = time()# your taskend = time()time_taken = end - start
print(time_taken, "seconds")

Here, we call the time function, which returns a representation of the current time when called.

start = time()
print(start)
# 1636163125.743031

If we simply print time() we will get this large number, which represents the Unix time — number of seconds that has passed since UTC 1 January 1970.

start = time() # 1636163481.538652 # your task that takes around 1 secondend = time() # 1636163482.542933 (the time one second later)time_taken = end - start # 1.0042810440063477 

This way, we can repeatedly call time() before and after our code, and print the difference between the 2 times to check how long our code takes to run.

One Problem With This Method

But what if we have many many functions that we want to time? Let’s say we have 5 different functions we want to time. Here’s how our code might look like if we time the function calls manually:

start = time()
function1()
end = time()
time_taken = round(end-start, 5)
print("function1", time_taken, "seconds")
start = time()
function2(arg1, arg2)
end = time()
time_taken = round(end-start, 5)
print("function2", time_taken, "seconds")
start = time()
function3(arg1)
end = time()
time_taken = round(end-start, 5)
print("function3", time_taken, "seconds")
start = time()
function4(arg1, arg2, arg3, arg4, arg5)
end = time()
time_taken = round(end-start, 5)
print("function4", time_taken…

--

--