我为程序编写了测试并检查了内存使用情况。由于某种原因,在函数中包装相同的操作会导致内存使用的多项式(或指数)增加。我正在使用memory_profiler来跟踪内存使用情况,Python 2.7.1。
代码:
def convertIntToBitint(number): return (pow(2, number - 1))
测试代码和结果(清理一下):
Line # Mem usage Increment Line Contents
23 9.070 MB 0.000 MB def test_convertBigIntToBitint(self):
24 9.070 MB 0.000 MB result1 = convertIntToBitint(21000)
25 9.070 MB 0.000 MB answer1 = pow(2, 20999)
27 10.496 MB 1.426 MB result2 = convertIntToBitint(5015280)
28 11.785 MB 1.289 MB answer2 = pow(2, 5015279)
30 70.621 MB 58.836 MB result3 = convertIntToBitint(121000000)
31 85.367 MB 14.746 MB answer3 = pow(2, 120999999)
为什么convertIntToBitint
会占用更多内存?为什么内存使用率不会线性增长?
有趣。不确定这是不是你的意思。
Line # Mem usage Increment Line Contents
23 9.074 MB 0.000 MB def test_convertBigIntToBitint(self):
24 56.691 MB 47.617 MB result3 = convertIntToBitint(121000000)
25 85.539 MB 28.848 MB answer3 = pow(2, 120999999)
26 85.539 MB 0.000 MB result2 = convertIntToBitint(5015280)
27 84.258 MB -1.281 MB answer2 = pow(2, 5015279)
28 83.773 MB -0.484 MB result1 = convertIntToBitint(21000)
29 81.211 MB -2.562 MB answer1 = pow(2, 20999)