习惯PySnooper的elapsed time,如何在Snoop中开启该功能?
在Snoop中启用耗时统计(Elapsed Time)功能
Snoop本身支持类似PySnooper的耗时统计功能,只需通过以下方式启用:
启用内置耗时统计
使用@watch装饰器时,添加show_time=True参数即可开启实时耗时追踪,示例代码:from snoop import watch @watch(show_time=True) def calculate_sum(a, b): result = a + b return result calculate_sum(3, 5)执行后,日志会显示从函数开始执行到每一步的累计耗时,和PySnooper的elapsed time效果一致。
自定义代码块耗时统计
如果需要针对特定代码块统计耗时,可以结合time模块手动实现,示例:from snoop import watch import time @watch def process_data(data): start = time.perf_counter() # 处理数据的第一步 processed = [x * 2 for x in data] snoop.print(f"数据预处理耗时: {time.perf_counter() - start:.4f}秒") # 后续操作 start = time.perf_counter() result = sum(processed) snoop.print(f"求和操作耗时: {time.perf_counter() - start:.4f}秒") return result这种方式能更灵活地追踪不同代码段的执行时间。
内容的提问来源于stack exchange,提问作者arthur
相关产品推荐
相关产品推荐

