Python元素访问performan

2024-09-28 01:32:12 发布

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

作为一个长时间的C++开发人员,我刚刚开始在Python中研究算法。我目前正在分析我的代码,以了解如何在Python中高效地编程。有一件事特别突出,我很高兴得到专家的解释。你知道吗

我为光线三角形相交编写了这个包装函数:

def rayIntersectsTriangle( origin , direction , meshData , poly , worldCoordinateVertices ):
    return mathutils.geometry.intersect_ray_tri( worldCoordinateVertices[ meshData.loops[ poly.loop_start ].vertex_index ],
                                                 worldCoordinateVertices[ meshData.loops[ poly.loop_start + 1 ].vertex_index ],
                                                 worldCoordinateVertices[ meshData.loops[ poly.loop_start + 2 ].vertex_index ],
                                                 direction , origin ) != None

在分析(使用cProfile)多次执行此函数的代码时,我得到以下结果:

ncalls  tottime  percall  cumtime  percall filename:lineno(function)
15694126   22.314    0.000   25.812    0.000 ****.py:176(rayIntersectsPoly)
[...]
15694126    3.497    0.000    3.497    0.000 {built-in method mathutils.geometry.intersect_ray_tri}

为什么这个包装会增加这么多开销?我唯一能看到的就是数组元素的访问。来自C++的这真的让我困惑:D<P>

在此方面的任何帮助都将不胜感激。我想尽快得到我的算法。你知道吗

提前谢谢!干杯!你知道吗


Tags: 函数代码算法loopindexoriginstartvertex
1条回答
网友
1楼 · 发布于 2024-09-28 01:32:12

相比之下,时间看起来很大,因为mathutils.geometry.intersect_ray_tri()太快了。该方法在扩展中实现,并以本机速度执行。你知道吗

该方法的Python时间为:

  • 创建新的函数框架(只有一个表达式,时间占比较大的比例)
  • 全局名称查找(这些是针对映射进行的,本地名称使用数组)。你知道吗
  • 属性查找,如mathutils.geometrymathutils.geometry.intersect_ray_tripoly.loop_start
  • 索引,所以worldCoordinateVertices[ ... ]。你知道吗

通过将其中一些结果缓存在本地名称或默认参数中,可以加快速度:

def rayIntersectsTriangle(
        origin, direction, meshData, poly, worldCoordinateVertices
        _intersect_ray_tri=mathutils.geometry.intersect_ray_tri):
    loop_start = poly.loop_start
    meshData_loops = meshData.loops
    return _intersect_ray_tri(
        worldCoordinateVertices[meshData_loops[loop_start].vertex_index],
        worldCoordinateVertices[meshData_loops[loop_start + 1].vertex_index],
        worldCoordinateVertices[meshData_loops[loop_start + 2].vertex_index],
        direction, origin) is not None

我还使用了is not None;这是建议测试None单例的指针操作。你知道吗

这将8个属性查找减少到2个,并删除mathutils的全局名称查找。你知道吗

不过,这些都是微观优化,只有在它们确实有影响的情况下才进行(例如,在代码中经常调用该方法)。如果这真的是您的瓶颈,请考虑使用Cython作为一种简单的方法,将此代码转换为一个编译扩展,该扩展也可以以本机速度运行。你知道吗

相关问题 更多 >

    热门问题