直接上代码:
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 # @Time : 2018/07/24 16:23 4 5 import itertools 6 import sys 7 import time 8 9 reps = 1000 # 测试重复次数 10 nums = 20000 # 测试时数字大小 11 12 13 def tester(func, *args): # 总体测试函数 14 start_time = time.time() 15 for i in xrange(reps): 16 func(*args) 17 elapsed = time.time() - start_time # 用time模块来测试,结束时间与开始时间差 18 return elapsed 19 20 21 def while_statement(): # while循环实现 22 res = [] 23 x = 0 24 while nums > x: 25 x += 1 26 res.append(abs(x)) 27 28 29 def for_statement(): # for循环实现 30 res = [] 31 for x in xrange(nums): 32 res.append(abs(x)) 33 34 35 def generator_expression(): # 生成器实现 36 res = list(abs(x) for x in xrange(nums)) 37 38 39 def list_comprehension(): # 列表生成式实现 40 res = [100] 41 res += [abs(x) for x in xrange(nums)] 42 43 44 def map_function(): # 内置函数map实现 45 res = [100] 46 res += map(abs, xrange(nums)) 47 48 49 def map_function2(): # 内置函数map实现 50 res = [100] 51 res.extend(map(abs, xrange(nums))) 52 53 54 def map_function3(): # 内置函数map实现 55 res = [100] 56 itertools.chain(res, map(abs, xrange(nums))) 57 58 59 if __name__ == '__main__': 60 print sys.version # 打印系统版本 61 tests = [ 62 while_statement, for_statement, 63 generator_expression, list_comprehension, 64 map_function, map_function2, 65 map_function3 66 ] 67 for test_func in tests: # 将待测函数放置列表中依次遍历 68 print test_func.__name__.ljust(20), ': ', tester(test_func) #
结果如下:
1 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:53:40) [MSC v.1500 64 bit (AMD64)] 2 while_statement : 2.53600001335 3 for_statement : 1.93700003624 4 generator_expression : 1.3639998436 5 list_comprehension : 1.06500005722 6 map_function : 0.90499997139 7 map_function2 : 0.899000167847 8 map_function3 : 0.824999809265
结论:
1)耗时:while > for > 列表生成式 > map函数;
2)连接list时,itertools的chain对象比直接+或者extand要快。
3)另外,以上range均使用xrange,相比range返回列表,xrange返回iterator, 实际测试表明,xrange比range快。