【Python】 for, list_comprehension, map_function, generator_expression效率比较

<pre name="code" class="python">import time, sys
reps = 1000
size = 10000

# 测试主体
def tester(func, *args):
	startTime = time.time()
	for i in range(reps):
		func(*args)
	elapsed = time.time() - startTime
	return elapsed

# for
def forStatement():
	res = []
	for x in range(size):
		res.append(abs(x))

# list comprehension
def listComprehension():
	res = [abs(x) for x in range(size)]

# map function
def mapFunction():
	res = map(abs, range(size))

def generatorExpression():
	res = list(abs(x) for x in range(size))

# 测试输出
print sys.version
tests = (forStatement, listComprehension, mapFunction, generatorExpression)
for testfunc in tests:
	print testfunc.__name__.ljust(20), '=>', tester(testfunc)


 
 

【Python】 for, list_comprehension, map_function, generator_expression效率比较_第1张图片

你可能感兴趣的:(list,function,python,map,for,compare,efficiency,comprehension)