我的列表理解比使用生成器表达式的等效代码更快。为什么呢?

时间:2016-02-01 19:28:18

标签: python python-3.x generator list-comprehension

here之前已经提出过类似的问题,但结论是sumlen之间存在差异。在我的测试中,我无法看到是什么让列表理解更快。我正在使用Python 3.4.2,当我加入列表理解与生成器时,我的计算机的性能差异大约为15-20%

我的代码:

import time

def timer(ta=[time.perf_counter()]):
    tb, ta[0] = ta[0], time.perf_counter()
    return ta[0]-tb

iterations = 10000000

gstr = ''.join(str(i) for i in range(iterations))
print('Generator: {:.3f} s'.format(timer()))

cstr = ''.join([str(i) for i in range(iterations)])
print('List comprehension: {:.3f} s'.format(timer()))

delta = 100-100*ctime/gtime
print()
print('List comprehension is {:.0f} % faster than     generator'.format(delta))

输出,即:

Generator: 4.772 s
List comprehension: 3.991 s

List comprehension is 16 % faster than generator

正如评论中所指出的,这是由于str.join()调用了两次项目。解释here但是当删除join()时,差异仍然存在:

gstr = list(str(i) for i in range(iterations))
print('Generator: {:.3f} s'.format(timer()))

lstr = list([str(i) for i in range(iterations)])
print('List of list comprehension: {:.3f} s'.format(timer()))

cstr = [str(i) for i in range(iterations)]
print('List comprehension: {:.3f} s'.format(timer()))

输出:

Generator: 4.088 s
List of list comprehension: 3.720 s
List comprehension: 3.397 s

即使列表清单的新列表仍然更快?

0 个答案:

没有答案