Amount of memory used in a function?

Which python module can I use to calculate the amount of memory spent executing a function? I'm using memory_profiler, but it shows the amount of memory spent by each line of the algorithm, in this case I want one that shows the total amount spent.

Upvotes: 1

Views: 2420

Answers (1)

ARK1375
ARK1375

Reputation: 818

You can use tracemalloc to do what memory_profiller does automatically. It's a little unfriendly but I think it does what you want to do pretty well.
Just follow the code snippet below.

import tracemalloc

def myFucn():
    tracemalloc.start()
    ## Your code
    print( tracemalloc..get_traced_memory())
    tracemalloc.stop()

The output is given in form of (current,peak),i.e, current memory is the memory the code is currently using and peak memory is the maximum space the program used while executing.

The code is from geeksforgeeks. Check it out for more info. Also, there are a couple of other methods to trace the memory explained inside the link. Make sure to check it out.

Upvotes: 2

Related Questions