当前位置: 首页 > news >正文

Timer 计时器

  • 写一个计时类
import timeclass Timer:def __init__(self):self.start_time = Noneself.end_time = Noneself.elapsed_time = None# 上下文管理器方法,支持 with 语句def __enter__(self):self.start_time = time.time()return selfdef __exit__(self, exc_type, exc_val, exc_tb):self.end_time = time.time()self.elapsed_time = self.end_time - self.start_timeprint(f"Elapsed time: {self.elapsed_time:.6f} seconds")# 手动计时方法def start(self):self.start_time = time.time()def stop(self):self.end_time = time.time()self.elapsed_time = self.end_time - self.start_timereturn self.elapsed_time# 装饰器方法,用来计时任意函数@staticmethoddef timer_decorator(func):def wrapper(*args, **kwargs):timer = Timer()  # 创建 Timer 实例timer.start()result = func(*args, **kwargs)timer.stop()print(f"Function '{func.__name__}' executed in {timer.elapsed_time:.6f} seconds")return resultreturn wrapper# 使用静态方法作为装饰器
@Timer.timer_decorator 
def example_function(n):return sum([i**2 for i in range(n)])# 调用函数
result = example_function(1000000)
  • 结果:
Function 'example_function' executed in 0.262828 seconds

http://www.mrgr.cn/news/42392.html

相关文章:

  • 《蓝桥杯算法入门》(C/C++、Java、Python三个版本)24年10月出版
  • 华为OD机试 - 无向图染色(Python/JS/C/C++ 2024 E卷 100分)
  • 两个wordpress网站共用一个数据库的数据表
  • 如何对物理系统进行数学建模?
  • CSS属性 - animation
  • 14 Shell Script正则表达式
  • Navicat Premium 12 for Mac中文永久版
  • 鸿蒙HarmonyOS开发生态:构建万物互联的未来
  • java高并发场景RabbitMQ的使用
  • 360浏览器时不时打不开csdn
  • 大厂笔试现已经禁用本地IDE怎么看
  • 系统架构设计师教程 第13章 13.2 表现层架构设计 笔记
  • 【ubuntu】Ubuntu20.04安装中文百度输入法
  • 我是如何写作的?
  • 使用 Python 实现图形学的着色器编程算法
  • C初阶(十二)do - while循环 --- 致敬革命烈士
  • 告别繁琐!用Flyon UI轻松实现高颜值网站!
  • 【LeetCode: 344. 反转字符串 | 双指针模拟】
  • 外包干了3个多月,技术退步明显。。。。。
  • Python并发编程挑战与解决方案