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

多进程场景下time.perf_counter等计时函数返回异常值求助

解决多进程测试代码中的几个问题

1. cpu_count输出绑定方法而非核心数

问题出在调用cpu_count时缺少括号,如果写成print(cpu_count)(而非print(cpu_count())),Python会输出函数对象本身而非执行结果。修正代码:

print(cpu_count())  # 加括号执行函数,输出实际核心数

2. time.perf_counter()返回异常大的数值

time.perf_counter()返回的是从系统启动以来的累计时间(或固定起始点的时间),而非目标代码段的执行耗时。你需要记录起始时间,计算时间差:

def main():
    print(cpu_count())
    start_time = time.perf_counter()  # 记录代码执行起始点

    a = Process(target=counter, args=(250000000,))
    b = Process(target=counter, args=(250000000,))
    c = Process(target=counter, args=(250000000,))
    d = Process(target=counter, args=(250000000,))
    
    a.start()
    b.start()
    c.start()
    d.start()

    a.join()
    b.join()
    c.join()
    d.join()

    elapsed_time = time.perf_counter() - start_time  # 计算实际耗时
    print("Finished in:", elapsed_time, "seconds")

这样就能得到实际运行的2-3秒左右的结果。

3. timeit.timeit()结果不合理

timeit默认会重复执行目标代码百万次,直接用它测试多进程代码容易出现环境适配问题。如果要用timeit测试,需要把多进程逻辑封装成独立函数,并指定合理的执行次数:

import timeit

def run_multiprocess():
    a = Process(target=counter, args=(250000000,))
    b = Process(target=counter, args=(250000000,))
    c = Process(target=counter, args=(250000000,))
    d = Process(target=counter, args=(250000000,))
    a.start()
    b.start()
    c.start()
    d.start()
    a.join()
    b.join()
    c.join()
    d.join()

# 指定仅执行1次,避免重复创建进程导致的异常结果
print(timeit.timeit(run_multiprocess, number=1))

注意:timeit的执行环境会重新导入模块,需确保多进程代码在if __name__ == "__main__":块外或做了正确处理,避免子进程重复执行主逻辑。

内容的提问来源于stack exchange,提问作者Yeasin Al Yeasa

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 12:23:09