Member-only story

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 

--

--

Liu Zuo Lin
Liu Zuo Lin

Written by Liu Zuo Lin

SWE @ Meta | [Ebook] 101 Things I Never Knew About Python: https://payhip.com/b/vywcf

No responses yet