Python Timer:三种监控你程序运行时间的方式

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'

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 在Python中,可以通过`time`模块来打印程序运行消耗时间。具体方法如下: ```python import time start_time = time.time() # 记录开始时间 # 程序代码 end_time = time.time() # 记录结束时间 elapsed_time = end_time - start_time # 计算运行时间 print("程序运行时间:{:.2f}s".format(elapsed_time)) ``` 其中,`time.time()`函数可以返回当前时间的时间戳,单位为秒。通过记录开始时间和结束时间,可以计算出程序运行时间,最后使用`print`函数打印出来即可。 需要注意的是,由于计算机的运行速度非常快,时间单位为秒可能过于粗略,因此可以使用`timeit`模块来精确测量代码运行时间。`timeit`模块可以自动运行多次代码,并计算平均运行时间,从而得到更准确的结果。 ### 回答2: 在Python中,我们可以使用`time`模块来计算程序的运行时间。具体步骤如下: 1. 首先,在你的Python脚本中导入`time`模块。 ``` import time ``` 2. 在程序的开始处记录当前时间。 ``` start_time = time.time() ``` 3. 在程序的结尾处再次记录当前时间。 ``` end_time = time.time() ``` 4. 计算程序的运行时间,即结束时间减去开始时间。 ``` elapsed_time = end_time - start_time ``` 5. 最后,打印出程序的运行时间。 ``` print("程序运行时间为:", elapsed_time, "秒") ``` 以上是使用Python打印程序运行消耗时间的基本方法。你可以根据具体需求进行适当的修改和扩展,比如将时间单位改为毫秒或分钟等。 需要注意的是,使用`time`模块计算的是程序从开始到结束的总运行时间,可能会受到计算机运行其他任务的影响。如果你希望精确计算某个具体操作的运行时间,可以使用`perf_counter()`函数替换`time()`函数,它会考虑当前系统时间的变化。 ### 回答3: 在Python中,我们可以使用`time`模块来计算程序运行的消耗时间。具体步骤如下: 首先,我们需要导入`time`模块: ```python import time ``` 然后,在我们需要计算消耗时间的代码块前后,分别添加`time`模块提供的两个函数:`time.time()`。第一个函数用于获取当前时间戳,我们将其保存在一个变量中,表示代码开始运行的时间。第二个函数同样获取当前时间戳,但是我们将其减去第一个时间戳,得到代码运行消耗的时间。 ```python start_time = time.time() # 你的代码 end_time = time.time() elapsed_time = end_time - start_time ``` 最后,我们可以将消耗的时间打印出来,如下所示: ```python print("代码运行消耗时间为:", elapsed_time, "秒") ``` 综合上述步骤,我们可以实现一个简单的计时器函数,如下所示: ```python import time def timer(): start_time = time.time() # 你的代码 end_time = time.time() elapsed_time = end_time - start_time print("代码运行消耗时间为:", elapsed_time, "秒") ``` 使用该计时器函数,你可以在需要计算程序运行消耗时间的代码块中调用它,然后就可以在控制台上看到程序运行的消耗时间了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值