Python generator

博客主要介绍了Python中Generator的特点。Generator所需内存较少,但在存储list的内存充足时,其性能较慢,速度约为list的一半。

Generator

Generator 需要的内存比较少

In [20]: nums_squared_gc = (num**2 for num in range(5000)) # list comprehension

In [21]: nums_squared_lc = [num**2 for num in range(5000)]  # generator comprehension

In [22]: sys.getsizeof(nums_squared_gc)
Out[22]: 120

In [23]: sys.getsizeof(nums_squared_lc)
Out[23]: 43040

Generator的Performance 比较慢 (若储list 的内存够多)

list 快 x 2 被

In [30]: import cProfile

In [31]: cProfile.run('sum([i for i in range(100000)])')
         5 function calls in 0.009 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.007    0.007    0.007    0.007 <string>:1(<listcomp>)
        1    0.001    0.001    0.008    0.008 <string>:1(<module>)
        1    0.000    0.000    0.009    0.009 {built-in method builtins.exec}
        1    0.001    0.001    0.001    0.001 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}



In [32]: cProfile.run('sum((i for i in range(100000)))')
         100005 function calls in 0.019 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   100001    0.009    0.000    0.009    0.000 <string>:1(<genexpr>)
        1    0.000    0.000    0.019    0.019 <string>:1(<module>)
        1    0.000    0.000    0.019    0.019 {built-in method builtins.exec}
        1    0.011    0.011    0.019    0.019 {built-in method builtins.sum}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler' objects}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值