• 设为首页
  • 收藏本站
  • 积分充值
  • VIP赞助
  • 手机版
  • 微博
  • 微信
    微信公众号 添加方式:
    1:搜索微信号(888888
    2:扫描左侧二维码
  • 快捷导航
    福建二哥 门户 查看主题

    Python中计时程序运行时间的几种常用方法

    发布者: 土豆服务器 | 发布时间: 2025-6-14 12:22| 查看数: 74| 评论数: 0|帖子模式

    前言

    在实际工作中,我们常常需要知道程序的实际运行时间(wall-clock time, real time)。本文就介绍了几种在Python中计时程序运行耗时的方法。

    1. 一般方法

    最为常见的方法,就是在代码的开头和结尾分别获取时间戳,然后两者之差便是程序运行时间。
    1. import time

    2. def do_something(nsec=0):
    3.         if isinstance(nsec, (int, float)):
    4.                 time.sleep(nsec)  # 模拟程序运行耗时

    5. if __name__ == "__main__":
    6.         start_time        = time.perf_counter()  # 记录开始时间戳
    7.         do_something(3)
    8.         do_something(1)
    9.         do_something(0.5)
    10.         end_time = time.perf_counter()  # 记录结束时间戳
    11.         print(f"耗时 {end_time - start_time:.3f} s")
    复制代码

    这是最简单直接的方法,但问题是当需要计时的部分很多的时候,会导致大量的重复代码。

    2. 基于上下文管理器

    相比之下,使用Python的上下文管理器(context manager)是更加优雅,复用性更好的解决方案。Python的上下文管理器机制是用来更加方便地管理如文件、数据库连接、锁等资源的,确保在使用结束后恰当地关闭及释放资源,以避免造成泄露。
    然而,上下文管理器的用途不仅限于资源的管理,其适合于所有的代码开始和结束的成对操作,就比如计时程序的运行时间。
    1. import time

    2. class Timer:
    3.         """
    4.         按照 xxh xxm xxs格式计时程序运行时间的计时上下文管理器
    5.         """
    6.         def __init__(self, code_part):
    7.                 self._part = code_part
    8.                
    9.         def __enter__(self):
    10.                 self._enter_time = time.perf_counter()
    11.                
    12.         def __exit__(self, *exc_args):  # 不做异常处理,因此将异常相关的参数打包
    13.                 time_span = time.perf_counter() - self._enter_time
    14.                 hours, seconds = divmod(time_span, 3600)
    15.                 minutes, seconds = divmod(seconds, 60)
    16.                 print(f"{self._part}耗时 {int(hours)}h {int(minutes)}m {seconds:.2f}s")

    17. def do_something(nsec=0):
    18.         if isinstance(nsec, (int, float)):
    19.                 time.sleep(nsec)  # 模拟程序运行耗时

    20. if __name__ == "__main__":
    21.         with Timer("Main"):
    22.                 with Timer("Part1"):
    23.                         do_something(0.3)
    24.                 with Timer("Part2"), open("demo_file.txt", "wt") as f:
    25.                         f.write("Hello, World\n")
    26.                         do_something(2)
    27.                 do_something(1)
    复制代码


    3. 基于装饰器

    使用Python的装饰器特性,可以十分方便地在函数水平添加计时器,计时单个函数的运行时间。
    1. import time
    2. from functools import wraps

    3. def timer(func):
    4.         @wraps(func)
    5.         def inner(*args, **kwargs):
    6.                 start_time = time.perf_counter()
    7.                 retval = func(*args, **kwargs)
    8.                 time_span = time.perf_counter() - start_time
    9.                 hours, seconds = divmod(time_span, 3600)
    10.                 minutes, seconds = divmod(seconds, 60)
    11.                 print(f"{func.__name__}耗时 {int(hours)}h {int(minutes)}m {seconds:.2f}s")
    12.                 return retval
    13.         return inner

    14. @timer
    15. def do_something(nsec=0):
    16.         if isinstance(nsec, (int, float)):
    17.                 time.sleep(nsec)  # 模拟程序运行耗时

    18. @timer
    19. def main():
    20.         do_something(1)
    21.         time.sleep(0.5)

    22. if __name__ == "__main__":
    23.         main()       
    复制代码


    总结

    到此这篇关于Python中计时程序运行时间的几种常用方法的文章就介绍到这了,更多相关Python计时程序运行时间方法内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    来源:https://www.jb51.net/python/339881lje.htm
    免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

    本帖子中包含更多资源

    您需要 登录 才可以下载或查看,没有账号?立即注册

    ×

    最新评论

    QQ Archiver 手机版 小黑屋 福建二哥 ( 闽ICP备2022004717号|闽公网安备35052402000345号 )

    Powered by Discuz! X3.5 © 2001-2023

    快速回复 返回顶部 返回列表