2

我们有一些用 python 编写的代码,它使用了一些实际上只是“结构”的类——这些类的实例只有一堆字段,没有方法。例子:

class ResProperties:
    def __init__(self):
        self.endDayUtilities = 0
        self.marginalUtilities = []
        self.held = 0
        self.idleResource = True
        self.experience = 0.0
        self.resSetAside = 0
        self.unitsGatheredToday = 0

我们的主要代码使用了这个类的一堆实例。

为了加快代码速度,我想我会对这个类进行 cython 化:

cdef class ResProperties:

    cdef public float endDayUtilities
    cdef public list marginalUtilities
    cdef public int held
    cdef public int idleResource
    cdef public float experience
    cdef public int resSetAside
    cdef public int unitsGatheredToday

    def __init__(self):
        self.endDayUtilities = 0
        # etc: code just like above.

但是,结果是代码现在运行速度慢了 25%!

我如何找出导致代码现在运行速度变慢的原因?

谢谢。

4

1 回答 1

5

您将这些类转换为 Cython,但仍在 Python 代码中使用它们?

将数据从 C 转换为 Python 并返回会产生开销。例如,您的endDayUtilities成员是 C 样式的浮点数。当您从 Python 访问它时,float()必须先构造一个对象,然后您的 Python 代码才能对其进行任何操作。当您从 Python 分配给该属性时,同样的事情必须反过来发生。

在我的脑海中,我估计这些数据转换的性能开销在......哦,大约 25%。:-)

在将一些使用该数据的代码移至 Cython之前,您不会看到性能提升。基本上,你在C-land停留的时间越长,你就会做得越好。来来回回会杀了你。

作为另一种更简单的方法,您可能想尝试 Psyco 或 PyPy 而不是 Cython。

于 2012-05-22T23:06:47.903 回答