如何检查 Python 程序在运行时使用了多少内存

问题描述

在 Python 3.x 中,我们如何报告程序使用了多少内存?

我想使用消耗的内存(如指标)比较同一问题的不同解决方案。

例如,消耗的内存来自:

import itertools

def queens ():
    for p in itertools.permutations (range (8) ):
        yield [x for x in enumerate (p) ]

for q in queens ():
    err = False
    for a,b in ( (a,b) for a in q for b in q if a [0] < b [0] ):
        if abs (a [0] - b [0] ) == abs (a [1] - b [1] ):
            err = True
            break
    if not err: print (q)

消耗的内存来自:

SIZE=8
A=[0] * SIZE  # Array solution
s=0  # Global variable to count 'solutions',you can delete it!
t=0  # Global variable to count recursion 'tests',you can delete it!

def test(queen,col):
    global t
    t+=1
    for i in range(1,queen):
        if(A[queen-i-1]==col): return 0     # Test vertical
        if(A[queen-i-1]==col-i): return 0   # Test diagonal 1 (\)
        if(A[queen-i-1]==col+i): return 0   # Test diagonal 2 (/)
    return 1

def play(queen):
    global s
    for col in range(1,SIZE+1):
        if(test(queen,col)):     # If I can play the queen...
            A[queen-1]=col       # Add queen to the solution Array
            if(queen==SIZE):     # If the last queen was played,this is a solution
                s+=1
                print("Solution: {},{},{}".format(s,t,A))
            else:
                play(queen+1);   # If not last queen,play the next one
            A[queen-1]=0         # Clean the solution Array

play(1)  # Start putting first queen

解决方法

我发现了一些有趣的链接:

总而言之,一种解决方案是:

import tracemalloc
tracemalloc.start()

#
# code to test here
#

current,peak = tracemalloc.get_traced_memory()
print(f"Current memory usage is {current / 10**3}KB; Peak was {peak / 10**3}KB; Diff = {(peak - current) / 10**3}KB")
tracemalloc.stop()