作为一个长时间的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>
在此方面的任何帮助都将不胜感激。我想尽快得到我的算法。你知道吗
提前谢谢!干杯!你知道吗
相比之下,时间看起来很大,因为
mathutils.geometry.intersect_ray_tri()
太快了。该方法在扩展中实现,并以本机速度执行。你知道吗该方法的Python时间为:
mathutils.geometry
和mathutils.geometry.intersect_ray_tri
和poly.loop_start
worldCoordinateVertices[ ... ]
。你知道吗通过将其中一些结果缓存在本地名称或默认参数中,可以加快速度:
我还使用了
is not None
;这是建议测试None
单例的指针操作。你知道吗这将8个属性查找减少到2个,并删除
mathutils
的全局名称查找。你知道吗不过,这些都是微观优化,只有在它们确实有影响的情况下才进行(例如,在代码中经常调用该方法)。如果这真的是您的瓶颈,请考虑使用Cython作为一种简单的方法,将此代码转换为一个编译扩展,该扩展也可以以本机速度运行。你知道吗
相关问题 更多 >
编程相关推荐