Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何找出为什么cython代码会减慢速度?_Python_Optimization_Cython - Fatal编程技术网

Python 如何找出为什么cython代码会减慢速度?

Python 如何找出为什么cython代码会减慢速度?,python,optimization,cython,Python,Optimization,Cython,我们有一些用python编写的代码,其中使用了一些实际上只是“结构”的类——这些类的实例中只有一堆字段,没有方法。例如: class ResProperties: def __init__(self): self.endDayUtilities = 0 self.marginalUtilities = [] self.held = 0 self.idleResource = True self.experie

我们有一些用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
我们的主代码使用这个类的一组实例

为了加快代码的速度,我想我应该将这个类化:

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%左右

我如何找出是什么导致代码现在运行较慢


谢谢。

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

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

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

除非将使用该数据的部分代码移动到Cython,否则性能不会得到提升。基本上,你在C-land呆得越多,你会做得越好。来回走动会害死你的


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

“代码”运行速度慢25%?什么代码?你是如何衡量这种减速的?如果类只是属性的容器,为什么不使用namedtuple呢?代码是一个更大的模拟项目的一部分。我有一个标准配置,在我的机器上运行大约需要58秒。随着时间的变化,它上升到了80秒左右。