为什么发电机更快? [英] Why are generators faster?

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

问题描述

我知道生成器比迭代器快.我也了解可以使用for循环语法来实现生成器.例如:

I understand that generators are faster than iterators. I also understand that generators can be implemented using for loop syntax. For example:

    import time 


startT = time.time()


def myGen(n):
    for i in range(n):
        yield x         


def myIter(n):
    for i in range(n):
        pass

def main():
    n=100
    startT=time.time()
    myIter(n)
    print 'myIter took ', time.time() - startT

    startT=time.time()
    myGen(n)
    print 'myGen(n) took ', time.time() - startT

这只是结果的一个示例:

This is just one example of the results:

myIter took 0.09234782
myGen(n) took 0.017847266

由于这使用了for循环语法,所以我不明白它比迭代器快多少.该生成器使用迭代器,因为"for"循环是使用迭代器实现的.如果您对这些时间进行计时,则生成器将始终更快.为什么当生成器使用迭代器时会如此?

Since this uses the for loop syntax, then I don't understand how it is faster than an iterator. This generator uses an iterator, because the "for" loop is implemented using an iterator. If you time these, the generator is consistently faster. Why is this, when the generator uses an iterator?

谢谢.

推荐答案

在您的代码中,myIter(n)实际上确实有效-循环了100次.

In your code, myIter(n) actually does work -- it loops 100 times.

myGen(n)只需构建生成器-就是这样.它不会计数到100.您要做的只是计时构建对象所需的时间,而您计时的方式却不可靠.如果我们使用timeit(此处使用IPython使事情更简单):

myGen(n), on the other hand, simply builds the generator -- and that's it. It doesn't count to 100. All you're doing is timing how long it takes to build the object, and you're timing it in an unreliable way. If we use timeit (here using IPython to make things simpler):

>>> %timeit myIter(100)
1000000 loops, best of 3: 1 µs per loop
>>> %timeit myGen(100)
10000000 loops, best of 3: 163 ns per loop
>>> %timeit myGen(10**1000)
10000000 loops, best of 3: 163 ns per loop

并且我们看到myGen(n)时间与n是独立的,因为它没有做任何事情.实际上,我们可以看到您的代码从未以其他方式执行:

And we see that the myGen(n) time is independent of n, because it's not doing anything. In fact, we can see your code was never executed another way:

>>> list(myGen(100))
Traceback (most recent call last):
  File "<ipython-input-11-dd43d937402a>", line 1, in <module>
    list(myGen(100))
  File "<ipython-input-1-ba968e48e9fd>", line 3, in myGen
    yield x
NameError: name 'x' is not defined

如果我们纠正了这种错字,然后尝试一种快速消耗生成器的方法,我们将得到类似

If we fix this typo, and then try a fast way to consume the generator, we get something like

>>> %timeit myIter(100)
1000000 loops, best of 3: 1 µs per loop
>>> %timeit consume(myGen(100), 100)
100000 loops, best of 3: 3.44 µs per loop

和生成器版本较慢,这是经常发生的情况.

and the generator version is slower, as is often the case.

这篇关于为什么发电机更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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