V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
feather12315
V2EX  ›  问与答

Python 生成器

  •  
  •   feather12315 · 2016-04-03 21:54:31 +08:00 · 1336 次点击
    这是一个创建于 2996 天前的主题,其中的信息可能已经有所发展或是发生改变。

    对生成器不算了解,只是会用。可现在遇到了一个问题:

    def test():
        a = 1
        b = 2
        c = 3
        while True:
            yield c
            c += 1
    

    执行这段代码, a, b 变量还占用空间吗?

    若占用的话,有啥办法可以实现相同的功能而避免 a b 变量占用空间呢?

    实际情况是内存有点小, yield 的是一个回调函数,不想办法压榨内存的话会溢出。。。

    5 条回复    2016-04-05 12:27:04 +08:00
    lecher
        1
    lecher  
       2016-04-03 23:14:11 +08:00   ❤️ 2
    python 有内存分析的模块: memory_profiler
    用 pip 安装之后,可以通过在方法前加 @profile 之后执行 python -m memory_profiler filename.py 检查内存情况

    代码和变量都会占用内存,生成器在引用之后,只要引用数大于 0 ,是不会释放里面声明的内容的。
    feather12315
        2
    feather12315  
    OP
       2016-04-03 23:24:59 +08:00
    @lecher Thanks. 我看看这
    julyclyde
        3
    julyclyde  
       2016-04-05 10:56:20 +08:00
    @lecher 试了试,貌似对 generator 函数, memory_profiler 无效。不知道原理
    julyclyde
        4
    julyclyde  
       2016-04-05 10:59:47 +08:00   ❤️ 1
    我猜可能是因为 generator 函数没有 return , decorator 不知道它什么时候完成的
    feather12315
        5
    feather12315  
    OP
       2016-04-05 12:27:04 +08:00 via Android
    @julyclyde 唔。最近有些忙,我还没看。。谢谢你啦。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   943 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:35 · PVG 03:35 · LAX 12:35 · JFK 15:35
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.