收益比收益慢.为什么? [英] yield slower than return. why?

查看:50
本文介绍了收益比收益慢.为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了两个功能相同的函数 f 和 g

I wrote two function f and g with same functionality

def f(l, count):
    if count > 1:
        for i in f(l, count-1):
            yield i + 1
    else:

        yield from l

for i in f(range(100000),900):
    pass
print('f')

def g(l, count):
    if count > 1:
        tmp = []
        for i in g(l, count-1):
            tmp.append(i+1)
        return tmp
    else:
        return l
for i in g(range(100000),900):
    pass
print('f')

还有我我认为 f 应该更快,但 g 在运行时更快

and i I think f shuold be faster but g is faster when in run it

g 时间

real    0m5.977s
user    0m5.956s
sys     0m0.020s

f 时间

real    0m7.389s
user    0m7.376s
sys     0m0.012s

推荐答案

产生结果的解决方案和计算完整结果的解决方案之间有几个很大的区别.

There are a couple of big differences between a solution that yields a result and one that computes the complete result.

yield 一直返回下一个结果,直到用完为止,而完整的计算总是完全完成,所以如果你有一个可能提前终止计算的测试(通常是这种情况),yield 方法只会被调用足够多的次数来满足该标准 - 这通常会产生更快的代码.

The yield keeps returning the next result until exhausted while the complete calculation is always done fully so if you had a test that might terminate your calculation early, (often the case), the yield method will only be called enough times to meet that criteria - this often results in faster code.

yield 结果只消耗足够的内存来保存生成器和任何时刻的单个结果 - 完整计算消耗足够的内存来一次保存所有结果.当您获得非常大的数据集时,这些数据集可以区分大小不一的运行和崩溃的数据.

The yield result only consumes enough memory to hold the generator and a single result at any moment in time - the full calculation consumes enough memory to hold all of the results at once. When you get to really large data sets that can make the difference between something that runs regardless of the size and something that crashes.

因此,每次操作的 yield 成本略高,但在不耗尽结果的情况下更可靠且通常更快.

So yield is slightly more expensive, per operation, but much more reliable and often faster in cases where you don't exhaust the results.

这篇关于收益比收益慢.为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆