方法:
def f1(lIn):
l1 = sorted(lIn)
l2 = [i for i in l1 if i<0.5]
return [i*i for i in l2]
def f2(lIn):
l1 = [i for i in lIn if i<0.5]
l2 = sorted(l1)
return [i*i for i in l2]
def f3(lIn):
l1 = [i*i for i in lIn]
l2 = sorted(l1)
return [i for i in l1 if i<(0.5*0.5)]
import random
import cProfile
lIn = [random.random() for i in range(100000)]
cProfile.run('f1(lIn)')
cProfile.run('f2(lIn)')
cProfile.run('f3(lIn)')
结果:
D:\Python\Python38\python.exe D:/python_learn/lambda_test/test.py
7 function calls in 0.036 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.002 0.002 0.036 0.036 <string>:1(<module>)
1 0.000 0.000 0.034 0.034 test.py:118(f1)
1 0.011 0.011 0.011 0.011 test.py:120(<listcomp>)
1 0.006 0.006 0.006 0.006 test.py:121(<listcomp>)
1 0.000 0.000 0.036 0.036 {built-in method builtins.exec}
1 0.017 0.017 0.017 0.017 {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.018 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.001 0.001 0.018 0.018 <string>:1(<module>)
1 0.000 0.000 0.017 0.017 test.py:122(f2)
1 0.005 0.005 0.005 0.005 test.py:123(<listcomp>)
1 0.003 0.003 0.003 0.003 test.py:125(<listcomp>)
1 0.000 0.000 0.018 0.018 {built-in method builtins.exec}
1 0.008 0.008 0.008 0.008 {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.031 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.003 0.003 0.031 0.031 <string>:1(<module>)
1 0.000 0.000 0.029 0.029 test.py:126(f3)
1 0.007 0.007 0.007 0.007 test.py:127(<listcomp>)
1 0.005 0.005 0.005 0.005 test.py:129(<listcomp>)
1 0.000 0.000 0.031 0.031 {built-in method builtins.exec}
1 0.017 0.017 0.017 0.017 {built-in method builtins.sorted}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Process finished with exit code 0
本文通过对比三段Python代码的运行效率,深入分析了不同算法在处理大量随机数时的时间消耗。实验使用cProfile模块进行性能剖析,揭示了排序与筛选操作的不同组合对整体性能的影响。
227

被折叠的 条评论
为什么被折叠?



