为什么Python中的line_profiler时间不正确?

0 投票
1 回答
1202 浏览
提问于 2025-04-18 05:17

我刚开始接触Python中的line_profiler这个工具。我在看结果的时候,是不是理解错了?为什么下面的输出结果加起来不是1.67554秒,而是加起来是3.918秒(2426873微秒 + 1491105微秒)呢?谢谢!

# test.py
import numpy as np
def tf():
    arr = np.random.randn(3000,6000)
    np.where(arr>1,arr,np.nan)


import test
%lprun -f test.tf test.tf()

Timer unit: 4.27654e-07 s

File: test.py
Function: tf at line 9
Total time: 1.67554 s

Line #      Hits         Time  Per Hit   % Time  Line Contents
==============================================================
     9                                           def tf():
    10         1      2426873 2426873.0     61.9      arr = np.random.randn(3000,6000)
    11         1      1491105 1491105.0     38.1      np.where(arr>1,arr,np.nan)

1 个回答

3

你看错时间了,那些不是微秒

根据文档

时间:执行这一行代码所花费的总时间,以计时器的单位来表示。在表格之前的头部信息中,你会看到一行“计时器单位:”给出了转换成秒的换算因子。这个换算因子在不同的系统上可能会有所不同。

这是我特别强调的。你的输出显示每个计时器单位大约是0.428微秒。如果你用这些单位乘以计时器单位的值,总数是匹配的:

>>> unit = 4.27654e-07
>>> 2426873 * unit + 1491105 * unit
1.675538963612

撰写回答