按执行效率从高到底排序:f2,f1,f3
要求证明这个答案是对的
所以要分析代码的性能,计算出性能时间
方法一:使用python性能分析模块 cProfile
1 import random 2 def f1(lin): 3 l1 = sorted(lin) 4 l2 = [i for i in l1 if i<0.5] 5 return [i*i for i in l2] 6 def f2(lin): 7 l1 = [i for i in lin if i<0.5] 8 l2 = sorted(l1) 9 return [i*i for i in l2] 10 def f3(lin): 11 l1 = [i*i for i in lin] 12 l2 = sorted(l1) 13 return [i for i in l1 if i<(0.5*0.5)] 14 15 if __name__ == "__main__": 16 import cProfile 17 lin = [random.random() for i in range(10000)] 18 cProfile.run('f1(lin)') 19 cProfile.run("f2(lin)") 20 cProfile.run('f3(lin)') 21
执行结果:
7 function calls in 0.007 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.007 0.007 <ipython-input-2-b2915fa74d28>:2(f1) 1 0.001 0.001 0.001 0.001 <ipython-input-2-b2915fa74d28>:4(<listcomp>) 1 0.000 0.000 0.000 0.000 <ipython-input-2-b2915fa74d28>:5(<listcomp>) 1 0.000 0.000 0.007 0.007 <string>:1(<module>) 1 0.000 0.000 0.007 0.007 {built-in method builtins.exec} 1 0.006 0.006 0.006 0.006 {built-in method builtins.sorted} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 7 function calls in 0.005 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.004 0.004 <ipython-input-2-b2915fa74d28>:6(f2) 1 0.001 0.001 0.001 0.001 <ipython-input-2-b2915fa74d28>:7(<listcomp>) 1 0.001 0.001 0.001 0.001 <ipython-input-2-b2915fa74d28>:9(<listcomp>) 1 0.000 0.000 0.005 0.005 <string>:1(<module>) 1 0.000 0.000 0.005 0.005 {built-in method builtins.exec} 1 0.003 0.003 0.003 0.003 {built-in method builtins.sorted} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects} 7 function calls in 0.008 seconds Ordered by: standard name ncalls tottime percall cumtime percall filename:lineno(function) 1 0.000 0.000 0.008 0.008 <ipython-input-2-b2915fa74d28>:10(f3) 1 0.001 0.001 0.001 0.001 <ipython-input-2-b2915fa74d28>:11(<listcomp>) 1 0.001 0.001 0.001 0.001 <ipython-input-2-b2915fa74d28>:13(<listcomp>) 1 0.000 0.000 0.008 0.008 <string>:1(<module>) 1 0.000 0.000 0.008 0.008 {built-in method builtins.exec} 1 0.005 0.005 0.005 0.005 {built-in method builtins.sorted} 1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
方法二:使用time模块,我们只修改主函数
1 if __name__ == "__main__": 2 import time 3 lin = [random.random() for i in range(10000)] 4 t1 = time.time() 5 f1(lin) 6 t2 = time.time() 7 f2(lin) 8 t3 = time.time() 9 f3(lin) 10 t4 = time.time() 11 print('f1运行时间:',t2-t1) 12 print('f2运行时间:',t3-t2) 13 print('f3运行时间:',t4-t3)
执行结果:
f1运行时间: 0.0059967041015625 f2运行时间: 0.003997087478637695 f3运行时间: 0.00999307632446289