hutool.core.text.stop_watch¶
秒表计时器模块,对应 Java Hutool 的 cn.hutool.core.date.StopWatch。
Module Contents¶
Classes¶
API¶
- class hutool.core.text.stop_watch.TaskInfo(task_name: str, time_nanos: int)¶
任务信息,记录单个任务的名称和耗时。
Initialization
- property time_seconds: float¶
耗时(秒)。
- property time_millis: float¶
耗时(毫秒)。
- __repr__() str¶
- class hutool.core.text.stop_watch.StopWatch(id_: str = '', keep_task_list: bool = True)¶
秒表封装,用于存储一组任务的耗时时间并一次性打印对比。
与 Java Hutool 的 cn.hutool.core.date.StopWatch 对应。
用法:
sw = StopWatch("my_task") sw.start("step1") # ... 操作 ... sw.stop() sw.start("step2") # ... 操作 ... sw.stop() print(sw.pretty_print())
- 参数:
id – 秒表标识
keep_task_list – 是否保留任务列表
Initialization
- property id: str¶
获取秒表标识。
- set_keep_task_list(keep: bool) None¶
设置是否保留任务列表。
- 参数:
keep – 是否保留
- start(task_name: str = '') None¶
开始新任务。
- 参数:
task_name – 任务名称
- 抛出:
RuntimeError – 前一个任务未结束
- stop() None¶
停止当前任务。
- 抛出:
RuntimeError – 没有运行中的任务
- is_running() bool¶
是否有运行中的任务。
- current_task_name() Optional[str]¶
获取当前任务名,None 表示无任务。
- property last_task_info: Optional[hutool.core.text.stop_watch.TaskInfo]¶
获取最后一个任务信息。
- property total_time_nanos: int¶
总耗时(纳秒)。
- property total_time_millis: float¶
总耗时(毫秒)。
- property total_time_seconds: float¶
总耗时(秒)。
- property task_count: int¶
已完成任务数。
- property task_list: List[hutool.core.text.stop_watch.TaskInfo]¶
获取任务列表。
- get_task_info(task_name: str) Optional[hutool.core.text.stop_watch.TaskInfo]¶
根据任务名获取任务信息。
- 参数:
task_name – 任务名称
- 返回:
TaskInfo 或 None
- pretty_print() str¶
以可读格式打印所有任务耗时。
- 返回:
格式化的任务耗时字符串
- __repr__() str¶