You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何time.perf_counter()返回极大数值?Python计时异常问询

问题分析与解决方案

1. 关于time.perf_counter()的误解

你混淆了time.perf_counter()的实际作用:它返回的是从系统某个固定基准点(通常是系统启动时刻)开始流逝的累计秒数,并非你的程序启动后运行的时间。110000秒约等于30.5小时,这个数值完全符合系统运行时长的逻辑,和你的短程序本身无关。

2. 线程初始化的错误

你的线程代码存在明显问题:threading.Thread(target=hi())会立即执行hi()函数,并将函数的返回值(这里是None)赋值给target参数,而不是让线程去执行hi函数。正确的写法是传递函数对象本身:

x = threading.Thread(target=hi)

如果需要给hi传递参数,使用args参数指定,例如:

x = threading.Thread(target=hi, args=(arg1, arg2))

3. 正确的程序计时方式

如果要统计代码段或程序的运行时长,需要在执行前后分别调用time.perf_counter(),再计算差值:

import time
import threading

def hi():
    pass

# 正确初始化线程
x = threading.Thread(target=hi)

# 开始计时
start_time = time.perf_counter()

# 启动线程并等待其结束
x.start()
x.join()

# 结束计时并计算时长
end_time = time.perf_counter()
print(f"运行时长: {end_time - start_time:.10f} 秒")

内容的提问来源于stack exchange,提问作者7k_ms

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:05:08