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

Python多线程中time.perf_counter()返回异常大值的原因咨询

问题解析:time.perf_counter()返回超大数值的原因

问题描述

正在学习Python多线程技术,尝试通过打印time.perf_counter()来查看主线程的程序运行耗时,结果返回了一个超大数值(614691.9609577),但实际耗时应该不到2秒,恳请解析该问题的原因。

相关代码

import threading
import time
    
def have_breakfast():
    time.sleep(3)
    print("You had breakfast")
def make_bed():
    time.sleep(4)
    print("You made your bed")
def study():
    time.sleep(5)
    print("You finish studying")
    
x = threading.Thread(target = have_breakfast, args = ())
x.start()
    
y = threading.Thread(target = make_bed, args = ())
y.start()
    
z = threading.Thread(target = study, args = ())
z.start()
    
x.join()
    
print(threading.active_count())
print(threading.enumerate())
print(time.perf_counter()) 

原因分析

  • time.perf_counter()返回的是从系统某个固定基准时间点到当前的累计秒数,并非程序自身的运行时长。直接调用它得到的自然是一个超大数值,和你要统计的程序耗时完全无关。
  • 另外你的代码里只对x线程调用了join(),主线程只会等待x执行完毕(约3秒),此时y和z还在后台运行,所以主线程实际运行时间大概3秒,和你说的“不到2秒”不符,可能是测试时的误判,但核心问题还是perf_counter的用法错误。

正确实现方式

要统计程序运行耗时,需要在程序开始时记录起始时间,结束时用当前时间减去起始时间。如果要统计所有线程完成后的总耗时,还需要对所有线程调用join():

import threading
import time
    
def have_breakfast():
    time.sleep(3)
    print("You had breakfast")
def make_bed():
    time.sleep(4)
    print("You made your bed")
def study():
    time.sleep(5)
    print("You finish studying")

# 记录程序起始时间
start_time = time.perf_counter()
    
x = threading.Thread(target=have_breakfast)
x.start()
    
y = threading.Thread(target=make_bed)
y.start()
    
z = threading.Thread(target=study)
z.start()

# 等待所有线程执行完成
x.join()
y.join()
z.join()
    
print(threading.active_count())
print(threading.enumerate())
# 计算并打印实际耗时
print(f"程序总运行耗时: {time.perf_counter() - start_time:.2f} 秒") 

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 03:20:17