本文介绍了python generator太慢了,无法使用它.我为什么要使用它?什么时候?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
最近我遇到一个问题,即在 iterator
, list comprehension
, iter(list comprehension)
和中,哪一个是最快的东西>发电机
.然后制作简单的代码,如下所示.
Recently I got question about which one is the most fastest thing among iterator
, list comprehension
, iter(list comprehension)
and generator
.and then make simple code as below.
n = 1000000
iter_a = iter(range(n))
list_comp_a = [i for i in range(n)]
iter_list_comp_a = iter([i for i in range(n)])
gene_a = (i for i in range(n))
import time
import numpy as np
for xs in [iter_a, list_comp_a, iter_list_comp_a, gene_a]:
start = time.time()
np.sum(xs)
end = time.time()
print((end-start)*100)
结果如下.
0.04439353942871094 # iterator
9.257078170776367 # list_comprehension
0.006318092346191406 # iterator of list_comprehension
7.491207122802734 # generator
发电机比其他东西要慢.我不知道什么时候有用?
generator is so slower than other thing.and I don't know when it is useful?
推荐答案
生成器
不会一次将所有元素存储在内存中.它们一次 yield
一次,这种行为使它们的存储效率更高.因此,当内存受到限制时,您可以使用它们.
generators
do not store all elements in a memory in one go. They yield
one at a time, and this behavior makes them memory efficient. Thus you can use them when memory is a constraint.
这篇关于python generator太慢了,无法使用它.我为什么要使用它?什么时候?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!