如何测量python函数的速度 [英] How to measure the speed of a python function
问题描述
我通常作为竞争对手在 www.codefights.com 上编写代码(函数).所以速度是代码的重要组成部分之一.我如何测量python语言中某个代码的速度,无论它是lambda函数还是def函数.
In 3 Step ;)
第 1 步:安装 line_profiler
pip install line_profiler
第 2 步:将 @profile
添加到您的代码中:
从时间导入睡眠@轮廓def so_slow(bar):睡觉(5)返回栏如果 __name__ == "__main__":so_slow(5)
第 3 步:测试您的代码:
kernprof -l -v your_code.py
结果
将配置文件结果写入 your_code.py.lprof计时单位:1e-06 s总时间:5.00283 秒文件:your_code.py功能:so_slow 在第 4 行Line # Hits Time Per Hit % 时间线内容==============================================================4 @个人资料5 def so_slow(bar):6 1 5002830 5002830.0 100.0 睡眠(5)7 1 2 2.0 0.0 返回棒
memory_profiler
您也可以使用 memory_profiler
,安装它,添加配置文件并调用它:
pip install memory_profilerpython -m memory_profiler your_code.py
结果:
文件名:your_code.pyLine # Mem 使用增量行内容================================================4 21.289 MiB 0.000 MiB @profile5 def so_slow(bar):6 21.289 MiB 0.000 MiB 睡眠(5)7 21.289 MiB 0.000 MiB 返回栏
更新:
您可以使用
I usually write codes(functions) on www.codefights.com as a competitor.So speed is one of the important part of the code . How can i measure the speed of a certain code in python language whether it is the lambda function or a def function .
In 3 Step ;)
Step 1: install line_profiler
pip install line_profiler
Step 2: Add @profile
to your code:
from time import sleep
@profile
def so_slow(bar):
sleep(5)
return bar
if __name__ == "__main__":
so_slow(5)
Step 3: Test your code:
kernprof -l -v your_code.py
Result
Wrote profile results to your_code.py.lprof
Timer unit: 1e-06 s
Total time: 5.00283 s
File: your_code.py
Function: so_slow at line 4
Line # Hits Time Per Hit % Time Line Contents
==============================================================
4 @profile
5 def so_slow(bar):
6 1 5002830 5002830.0 100.0 sleep(5)
7 1 2 2.0 0.0 return bar
memory_profiler
You can use memory_profiler
too, Install it, add profile and call it:
pip install memory_profiler
python -m memory_profiler your_code.py
Result:
Filename: your_code.py
Line # Mem usage Increment Line Contents
================================================
4 21.289 MiB 0.000 MiB @profile
5 def so_slow(bar):
6 21.289 MiB 0.000 MiB sleep(5)
7 21.289 MiB 0.000 MiB return bar
Update:
You can use objgraph to find memory leak
or draw a graph of your code:
from time import sleep
import objgraph
x = [1]
objgraph.show_backrefs([x], filename='sample-backref-graph.png')
def so_slow(bar):
sleep(5)
return bar
if __name__ == "__main__":
so_slow(5)
Result:
Reference : A guide to analyzing Python performance
这篇关于如何测量python函数的速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!