Profiling Your Code

How to Identify CPU and Memory Inefficiencies

Aren Carpenter
Published in
4 min readMar 12, 2021


To take your code to the next level, you need to ensure that your solutions are as efficient as possible! But how do we identify the bottlenecks in speed or memory usage? We profile!

CPU Usage and Timing

With a Custom Decorator

Decorators are functions that take other functions as arguments — an example of a higher-order function. In short, they add additional functionality (pun intended) without modifying the original function. In this case, our fn_timer decorator takes in a function and adds a timer by storing a start time, running the function, then storing an end time and returning a value of elapsed time!

import time
from functools import wraps

def fn_timer(function):
def function_timer(*args, **kwargs):
start_time = time.time()
result = function(*args, **kwargs)
end_time = time.time()
print(f"Runtime of {function.__name__} is {end_time -
start_time:.04} seconds.")
return result
return function_timer

def sort_list(n):
return sorted([i for i in range(n)])

if __name__ == "__main__":