python-3.x - 如何检查Python程序运行时使用了多少内存

标签 python-3.x memory-management

在 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()

关于python-3.x - 如何检查Python程序运行时使用了多少内存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66096117/

相关文章:

python - 由于比例因子和偏移量,导入 Python 时 NetCDF 数据精度下降

django - python : can't open file 'manage.py' : [Errno 2] No such file or directory

python - 打印换行符的最 Pythonic 方式

ios - CoreData 内存开销

ios - 如何查找并修复崩溃原因

c++ - 为什么存在奇特的指针?

python - 单击其中的小部件 [子] 时如何选择 QListWidgetItem

python - 将重复项放在一列上,打破另一列的联系

c++ - 删除与删除[]

ruby-on-rails - Unicorn:要使用多少个工作进程?