与 VSCode 相比,Python Idle 中的内存使用率更高

问题描述 投票:0回答:0

我一直在比较斐波那契数列的算法和两种算法的内存使用情况,并注意到与 vscode 相比,闲置时有额外的内存使用。

正在运行的代码是:

import tracemalloc

def fib_with_cache(n: int) -> int:
    cache = [0] * (n+1)
    cache[1] = 1
    if n > 1:
        cache[2] = 1
    for number in range(3, n+1):
        cache[number] = cache[number-1] + cache[number-2]
    return cache[n]


def fib_without_cache(n: int) -> int:
    a = 1
    b = 1
    if n == 0 or n == 1:
        return 1
    else:
        for i in range(1, n+1):
            temp = a
            a = b
            b = temp + a
        return b


tracemalloc.start()
fib_with_cache(10)
print("With cache", tracemalloc.get_traced_memory())
tracemalloc.stop()

print()

tracemalloc.start()
fib_without_cache(10)
print("Without cache", tracemalloc.get_traced_memory())
tracemalloc.stop()

我首先在空闲状态下运行代码并得到以下输出:

With cache (0, 168)

Without cache (456, 536)

我觉得这很奇怪,完全不像预期的那样,所以在 vscode 中尝试并得到:

With cache (0, 168)  

Without cache (0, 80)

重复测试显示相同的结果。交换函数调用的顺序也显示第二次调用处于空闲状态以使用更多内存:

Without cache (0, 80)

With cache (448, 616)

任何人都可以阐明为什么结果显示空闲时额外使用内存吗?

python memory python-idle
© www.soinside.com 2019 - 2024. All rights reserved.