len(primes(100000))
如不雅我们再次测量,我们可以获得以下结不雅:
Line # Mem usage Increment Line Contents
================================================
27 35.343750 MiB 0.000000 MiB @profile(precision=6)
28 def primes(n):
29 35.382812 MiB 0.039062 MiB if n == 2:
30 return [2]
31 35.382812 MiB 0.000000 MiB elif n < 2:
32 return []
33 35.386719 MiB 0.003906 MiB s = range(3, n + 1, 2)
34 35.417969 MiB 0.031250 MiB mroot = n ** 0.5
35 35.417969 MiB 0.000000 MiB half = (n + 1) / 2 - 1
37 35.421875 MiB 0.003906 MiB m = 3
38 58.019531 MiB 22.597656 MiB while m <= mroot:
39 58.019531 MiB 0.000000 MiB if s[i]:
46 58.019531 MiB 0.000000 MiB m = 2 * i + 3
40 58.019531 MiB 0.000000 MiB j = (m * m - 3) / 2
41 58.019531 MiB 0.000000 MiB s[j] = 0
43 58.019531 MiB 0.000000 MiB s[j] = 0
44 58.019531 MiB 0.000000 MiB j += m
47 58.019531 MiB 0.000000 MiB l = [2]
48 58.089844 MiB 0.070312 MiB for x in s:
49 58.089844 MiB 0.000000 MiB if x:
50 58.089844 MiB 0.000000 MiB l.append(x)
51 58.093750 MiB 0.003906 MiB return l
The governor "powersave" may decide which speed to use
很好,如今我们的内存消费降低到了 22.75 MiB。应用列表解析(list comprehension),我们还可以将消费再降低一点。
from memory_profiler import profile
@profile(precision=6)
def primes(n):
if n == 2:
return [2]
elif n < 2:
return []
half = (n + 1) / 2 - 1
i = 0
m = 3
if s[i]:
j = (m * m - 3) / 2memory_profiler 是一个可用来测量说冥器运行一个负载时的内存用量的库。你可以经由过程 pip 安装它:
s[j] = 0原文地址:
- https://pythonfiles.wordpress.com/2017/05/15/hunting-python-performance-setup/
- https://pythonfiles.wordpress.com/2017/05/18/hunting-python-performance-part-2/
while j < half:
s[j] = 0
j += m
i = i + 1
m = 2 * i + 3
return [2] + [x for x in s if x]
len(primes(100000))
再次测量:
Line # Mem usage Increment Line Contents
================================================
4 35.425781 MiB 0.000000 MiB @profile(precision=6)
5 def primes(n):
6 35.464844 MiB 0.039062 MiB if n == 2:
7 return [2]
8 35.464844 MiB 0.000000 MiB elif n < 2:
9 return []
10 35.464844 MiB 0.000000 MiB s = range(3, n + 1, 2)
11 35.500000 MiB 0.035156 MiB mroot = n ** 0.5
13 35.500000 MiB 0.000000 MiB i = 0
14 35.500000 MiB 0.000000 MiB m = 3
16 57.683594 MiB 0.000000 MiB if s[i]:
17 57.683594 MiB 0.000000 MiB j = (m * m - 3) / 2
18 57.683594 MiB 0.000000 MiB s[j] = 0
19 57.683594 MiB 0.000000 MiB while j < half:
20 57.683594 MiB 0.000000 MiB s[j] = 0
21 57.683594 MiB 0.000000 MiB j += m
22 57.683594 MiB 0.000000 MiB i = i + 1
23 57.683594 MiB 0.000000 MiB m = 2 * i + 3
24 57.847656 MiB 0.164062 MiB return [2] + [x for x in s if x]
我们最后的脚本仅消费 22.421875 MiB。比拟于第一个版本,差不多降低了 10%。
s = range(3, n + 1, 2)
【编辑推荐】
- 数据专家必知必会的7款Python对象
- Python调用C模块以及机能分析
- 一件有趣的事:我用 Python 爬了爬本身的微信同伙
- Python Crawler – 网信贷黑名单数据爬取
- 神经收集理论基本及Python实现
推荐阅读
【技巧沙龙】AI开辟者拭魅战营-7分钟打造1个定制技能。7月22号,我们等你一路! 读者自行测验测验可以想看源码戳这(https://github.com/damonare/Sorts),博主在github建了个库,读者可以>>>详细阅读
地址:http://www.17bianji.com/lsqh/36268.html
1/2 1

网友点评
精彩导读
科技快报
品牌展示