一、计算代码共运行了多少时间
time -p python3 lpdel.py
结果:
real 1.91
user 3.35
sys 0.35
- real表示的是执行脚本的总时间
- user表示的是执行脚本消耗的CPU时间。
- sys表示的是执行内核函数消耗的时间。
二、计算代码函数耗时时长
python
-
m cProfile
-
s cumulative timing_functions.py
python -m cProfile
: 这部分表示使用cProfile
模块执行代码性能分析。-s cumulative
: 这部分表示按照累积时间(cumulative time)对函数进行排序,以显示哪些函数花费了最多的总时间。
如果希望保存上述结果,先执行命令-o
,保存性能分析文件到指定的路径:
python -m cProfile -o profile.stats .\cal_pi.py -n 100000
可以使用pstats库对此文件进行分析:
import pstats
p = pstats.Stats("profile.stats")
p.sort_stats("cumulative")
p.print_stats() # 展示函数调用时间分析结果
p.print_callers() # 展示函数的被调用情况
p.print_callees() # 展示函数的调用情况
三、line_profiler
line_profiler
输出的结果更为简洁:在函数前加上装饰器@profile
通过命令行执行:
PS D:\work> kernprof -l -v .\cal_pi.py -n 1000000
pi is 3.141776
Wrote profile results to cal_pi.py.lprof
Timer unit: 1e-06 s
Total time: 5.69313 s
File: .\cal_pi.py
Function: cal_pi at line 10
Line # Hits Time Per Hit % Time Line Contents
==============================================================
10 @profile
11 def cal_pi(n_sims):
12 1 2.1 2.1 0.0 in_circle = 0
13 1000001 411368.5 0.4 7.2 for isims in range(n_sims):
14 1000000 3032114.9 3.0 53.3 x, y = np.random.rand(2)
15 1000000 1841899.0 1.8 32.4 if x**2 + y**2 < 1:
16 785444 407741.1 0.5 7.2 in_circle += 1
17 1 2.1 2.1 0.0 pi = in_circle/n_sims*4
18 1 0.9 0.9 0.0 return pirn pi
整个过程就变得非常直观,随机数生成占用了53%的时间,判断是否在圆内占用了32.8%的时间。如果想要进一步优化仅需要从这两个地方入手,另外注意循环这里其实也占用了大约7%的时间,如果能规避循环说不定也能对程序性能有较好的提升。
其他测试可以看下这个连接:10种检测Python程序运行时间、CPU和内存占用的方法_除了psutil,python还有哪些模块可以看服务器内存和cpu-CSDN博客
有问题请加博主微信进行沟通!
全部评论