奇怪的Python评测结果:小函数需要很长时间

2024-06-14 04:08:32 发布

您现在位置:Python中文网/ 问答频道 /正文

由于我的脚本处理大量数据,我一直在分析它以缩短执行时间。长跑之后,我发现了一个惊人的结果:

   ncalls  tottime  percall   cumtime  percall filename:lineno(function)
190158700 2488.387    0.000  5282.776    0.000 bitcoin_types.py:214(_read)
 17483627 1523.197    0.000  3385.274    0.000 script.py:124(parse)
 17479677 1289.881    0.000  1289.881    0.000 {method 'Put' of 'leveldb.LevelDB' objects}
 52439034 1279.769    0.000  2234.548    0.000 StringIO.py:208(write)
   201841 1127.547    0.006 17186.404    0.085 validate.py:35(block)
248980529 1089.813    0.000  1089.813    0.000 {len}
 15064476 1021.241    0.000  1021.241    0.000 {method 'Delete' of 'leveldb.LevelDB' objects}
 26434944 1010.258    0.000  1010.258    0.000 {method 'Get' of 'leveldb.LevelDB' objects}
 63334845  896.935    0.000  2904.124    0.000 bitcoin_types.py:222(read_uint8)
152052558  896.330    0.000   896.330    0.000 {method 'update' of '_hashlib.HASH' objects}
144965272  819.315    0.000   819.315    0.000 {method 'read' of 'file' objects}

您可以看到tottime = 2488.387,据我所知,这是运行函数的总时间,不包括内部调用,而cumtime包括在内。令人惊讶的是_read是一个非常小的函数:

def _read(f, n, h=None):
    data = f.read(n)

    if h is not None:
        h.update(data)

    return data

为什么_read要比tottime花这么长时间cumtime,即使它除了调用其他函数外几乎什么都不做?我希望cumtime >>>>> tottimeis not None这么昂贵的手术吗?我应该try-except它吗?你知道吗


Tags: of函数pynonereaddataobjects时间