How do I profile memory usage in Python?

前端 未结 8 658
无人及你
无人及你 2020-11-22 09:50

I\'ve recently become interested in algorithms and have begun exploring them by writing a naive implementation and then optimizing it in various ways.

I\'m already f

8条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 10:17

    Disclosure:

    • Applicable on Linux only
    • Reports memory used by the current process as a whole, not individual functions within

    But nice because of its simplicity:

    import resource
    def using(point=""):
        usage=resource.getrusage(resource.RUSAGE_SELF)
        return '''%s: usertime=%s systime=%s mem=%s mb
               '''%(point,usage[0],usage[1],
                    usage[2]/1024.0 )
    

    Just insert using("Label") where you want to see what's going on. For example

    print(using("before"))
    wrk = ["wasting mem"] * 1000000
    print(using("after"))
    
    >>> before: usertime=2.117053 systime=1.703466 mem=53.97265625 mb
    >>> after: usertime=2.12023 systime=1.70708 mem=60.8828125 mb
    

提交回复
热议问题