Python Timer:三种监控你程序运行时间的方式
原文地址: https://www.zhblog.net/go/python/advanced/python-timer?t=561
很多开发者知道Python是一个开发效率很高的编程语言,纯Python程序对比其它编译型语言如:C、Rust、或Java可能运行很慢。通过这篇教程,你将看到如何使用Python timer去监控你程序运行的速度。
Python Timers
首先,看一下本篇教程中会使用到的代码。随后你将添加Python Timer到程序中去监控它们的性能。你也将看到测量运行时间的一些简单方式。
Python Timer Functions
如果你看过Python内置的time模块,那么你应该知道测量时间的一些方法:
monotonic()
perf_counter()
process_time()
time()
Python3.7介绍了一些新方法,如thread_time(),还有上面方法的纳秒版本,以_ns后缀结尾。例如:perf_counter_ns()就是perf_counter()的纳秒版本。后面你会学习使用这些方法。注意,文档中perf_counter()的说明:
返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间。
你将使用perf_counter()方法去创建一个Python timer,然后去和其它的Python timer方法对比,知道为什么通常perf_counter()是最好的选择。
实例:下载
为了方便比较,你可以将不同的方法应用到相同的逻辑代码块中。
下面我们将使用realpython-reader包去Real Python上下载最新的教程。如果你的系统没有安装realpython-reader包,你可以使用pip进行安装。
pip install realpython-reader
安装完成后,你可以导入包reader。
新建程序文件latest_tutorial.py。代码由只有一个方法,从Real Python下载最新的教程,然后打印出来。
from reader import feed
def main():
"""Download and print the latest tutorial from Real Python"""
tutorial = feed.get_article(0)
print(tutorial)
if __name__ == "__main__":
main()
get_article()方法中参数0代表最新的一篇教程,1代表上一篇,以此类推。
当你运行这个例子,可能输出如下类似的内容
# Using Pandas and Python to Explore Your Dataset
Do you have a large dataset that's full of interesting insights, but you're
not sure where to start exploring it? Has your boss asked you to generate some
statistics from it, but they're not so easy to extract? These are precisely
the use cases where **Pandas** and Python can help you! With these tools,
you'll be able to slice a large dataset down into manageable parts and glean
insight from that information.
**In this tutorial, you 'll learn how to:**
......剩下下面文章内容......
代码可能需要一点时间运行,这取决于你的网络情况。所以它很适合使用Python timer来监控运行效率。
第一种Python Timer
添加系统计算器time.perf_counter()到这个例子中。它非常适合这段代码的计时。
perf_counter()以秒为单位返回某个未指定时刻的值。所以单次调用几乎没什么用,但在不同时刻两次调用你可以统计出花费的秒数:
>>> import time
>>> time.perf_counter()
23.3523745
>>> time.perf_counter() # a few seconds later
33.8999726
>>> 33.89 - 23.35
10.54
现在将Python timer添加到代码中:
from reader import feed
import time
def main():
"""Download and print the latest tutorial from Real Python"""
tic = time.perf_counter()
tutorial = feed.get_article(0)
toc = time.perf_counter()
print(f"Download the tutorial in {toc - tic:.2f} seconds.")
print(tutorial)
if __name__ == "__main__":
main()
我们在下载前后都调用了一次perf_counter(),然后计算时间差。
注意:打印中的f-string,它是python3.6以后可使用的一种格式化字符串方法。:.2f表示保留2位有效数字,处理的对象是toc -tic。
运行这个程序:
Download the tutorial in 4.36 seconds.
# Python args and kwargs: Demystified
Sometimes, when you look at a function definition in Python, you might see
that it takes two strange arguments: **`*args`** and **`**kwargs`**. If you'