import resource import tracemalloc as tm def memory(value): def decorator(function): def wrapper(*args, **kwargs): soft, hard = resource.getrlimit(resource.RLIMIT_AS) print("Memory Limit Set At: ", int(value * 1024)) # multiplyed by 1024 to convert to byte from KiloByte resource.setrlimit(resource.RLIMIT_AS, (int(value * 1024), hard)) try: tm.start() now_mem, peak_mem = tm.get_traced_memory() return_value = function(*args, **kwargs) new_mem, new_peak = tm.get_traced_memory() tm.stop() except MemoryError: resource.setrlimit(resource.RLIMIT_AS, (soft, hard)) # To let user handle the Exception raise MemoryError else: resource.setrlimit(resource.RLIMIT_AS, (soft, hard)) # To find memory useages of the function onlu return f"Memory Used: {new_peak - now_mem}" return wrapper return decorator def fibonacci(x): if x < 3: return 1 return fibonacci(x-1) + fibonacci(x-2) # did not decorate as this is recursive function print(memory(1)(fibonacci)(25)) # output # Memory Limit Set At: 1024 # Memory Used: 9606