Skip to main content
 首页 » 编程设计

python之在分析 Cython 代码时,什么是 `stringsource`

2025年05月04日6kevingrace

我正在尝试优化一个繁重的 Cython 函数。我正在根据以下教程进行分析 http://docs.cython.org/src/tutorial/profiling_tutorial.html .我的配置文件输出如下所示:

   ncalls  tottime  percall  cumtime  percall filename:lineno(function) 
        1    7.521    7.521   18.945   18.945 routing_cython_core.pyx:674(resolve_flat_regions_for_drainage) 
  6189250    4.964    0.000    4.964    0.000 stringsource:323(__cinit__) 
  6189250    2.978    0.000    7.942    0.000 stringsource:618(memoryview_cwrapper) 
  6009849    0.868    0.000    0.868    0.000 routing_cython_core.pyx:630(_is_flat) 
  6189250    0.838    0.000    0.838    0.000 stringsource:345(__dealloc__) 
  6189250    0.527    0.000    0.527    0.000 stringsource:624(memoryview_check) 
  1804189    0.507    0.000    0.683    0.000 routing_cython_core.pyx:646(_is_sink) 
    15141    0.378    0.000    0.378    0.000 {_gdal_array.BandRasterIONumPy} 
        3    0.066    0.022    0.086    0.029 /home/rpsharp/local/workspace/invest-natcap.invest-3/invest_natcap/raster_utils.py:235(new_raster_from_base_uri) 
    11763    0.048    0.000    0.395    0.000 /usr/lib/python2.7/dist-packages/osgeo/gdal_array.py:189(BandReadAsArray) 

我特别感兴趣的是多次调用 stringsource:323(__cinit__) 和 stringsource:618(memoryview_cwrapper) 的第 2 行和第 3 行。尽管我正在静态输入 numpy 数组,但 Google 发现了对内存 View 的引用,我没有在该函数中使用它。知道这些调用是什么以及我是否可以避免/优化它们?

请您参考如下方法:

好吧,事实证明我确实有一个内存 View 。我正在调用一个内联函数,该函数将静态类型的 numpy 数组传递给内存 View ,从而调用所有这些对 stringsource 的额外调用。用 numpy 类型替换函数调用中的 memoryview 类型修复了这个问题。