我的python脚本花在哪里了?我的cprofile/pstats跟踪中是否有“缺少时间”?

2024-06-26 18:06:58 发布

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

我正在尝试评测一个长时间运行的python脚本。该脚本使用gdal module对栅格GIS数据集进行一些空间分析。该脚本目前使用三个文件,主脚本在光栅像素上循环称为find_pixel_pairs.py,在lrucache.py中有一个简单的缓存,utils.py中有一些misc类。我在一个中等大小的数据集上分析了代码。pstats返回:

   p.sort_stats('cumulative').print_stats(20)
   Thu May  6 19:16:50 2010    phes.profile

   355483738 function calls in 11644.421 CPU seconds

   Ordered by: cumulative time
   List reduced from 86 to 20 due to restriction <20>

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.008    0.008 11644.421 11644.421 <string>:1(<module>)
        1 11064.926 11064.926 11644.413 11644.413 find_pixel_pairs.py:49(phes)
340135349  544.143    0.000  572.481    0.000 utils.py:173(extent_iterator)
  8831020   18.492    0.000   18.492    0.000 {range}
   231922    3.414    0.000    8.128    0.000 utils.py:152(get_block_in_bands)
   142739    1.303    0.000    4.173    0.000 utils.py:97(search_extent_rect)
   745181    1.936    0.000    2.500    0.000 find_pixel_pairs.py:40(is_no_data)
   285478    1.801    0.000    2.271    0.000 utils.py:98(intify)
   231922    1.198    0.000    2.013    0.000 utils.py:116(block_to_pixel_extent)
   695766    1.990    0.000    1.990    0.000 lrucache.py:42(get)
  1213166    1.265    0.000    1.265    0.000 {min}
  1031737    1.034    0.000    1.034    0.000 {isinstance}
   142740    0.563    0.000    0.909    0.000 utils.py:122(find_block_extent)
   463844    0.611    0.000    0.611    0.000 utils.py:112(block_to_pixel_coord)
   745274    0.565    0.000    0.565    0.000 {method 'append' of 'list' objects}
   285478    0.346    0.000    0.346    0.000 {max}
   285480    0.346    0.000    0.346    0.000 utils.py:109(pixel_coord_to_block_coord)
      324    0.002    0.000    0.188    0.001 utils.py:27(__init__)
      324    0.016    0.000    0.186    0.001 gdal.py:848(ReadAsArray)
        1    0.000    0.000    0.160    0.160 utils.py:50(__init__)

前两个调用包含主循环-整个分析。剩下的通话总计不到11644秒中的625次。剩下的11000秒花在哪里了?它们都在find_pixel_pairs.py的主循环中吗?如果是这样,我能找出哪些代码行占用了大部分时间?在


Tags: to数据代码py脚本utilsfindblock
3条回答

忘记函数和测量。Use this technique.只需在调试模式下运行它,然后按ctrl-C键几次。调用堆栈将精确地显示哪些代码行负责时间。在

添加:例如,暂停10次。如EOL所说,如果11000秒中有10400秒是直接在phes中度过的,那么在其中的9次暂停中,它将在那里停止。 另一方面,如果它在从phes调用的某个子例程中花费了很大一部分时间,那么您不仅可以看到它在该子例程中的位置,而且还可以看到调用它的行,这些行也负责时间,依此类推,一直到调用堆栈。在

Don't measure. Capture.

您是对的,大部分时间都花在find_pixel_pairs.py第49行的phes函数中。要了解更多信息,您需要将phes分解成更多的子功能,然后重新编译。在

每个函数或方法的代码执行所花费的时间在tottime列中。cumtime方法是在调用的函数中花费tottime+时间。在

在您的清单中,您可以看到您要查找的11000秒是由phes函数本身直接花费的。它只需要600秒。在

因此,您希望找到phes所花的时间,按照~unutbu的建议,将其分解为子功能并重新编译。在

相关问题 更多 >