python列表模拟中的性能问题

2024-09-30 16:20:23 发布

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

我目前正在用python3.4(miniconda)编写一个模拟。 整个模拟速度相当快,但一些模拟数据的测量速度非常慢,大约占整个模拟时间的35%。如果我能摆脱这个瓶颈,我希望我能提高整个模拟的性能。我花了相当长的时间想弄清楚如何做到这一点,但不幸的是,收效甚微。在模拟运行的每个阶段都会调用函数MeasureValues。你知道吗

如果有人知道如何改进代码,我将非常感激。你知道吗

谢谢你们。你知道吗

def MeasureValues(self, CurrentPeriod):
    if CurrentPeriod > self.WarmUp:
        self.ValueOne[CurrentPeriod] = self.FixedValueOne if self.Futurevalue[CurrentPeriod + self.Reload] > 0 else 0
        self.ValueTwo[CurrentPeriod] = self.VarValueTwo * self.AmountValueTwo[CurrentPeriod]
        self.ValueThree[CurrentPeriod] = self.VarValueThree  * self.AmountValueThree[CurrentPeriod]
        self.SumOfValues[CurrentPeriod] = self.ValueOne[CurrentPeriod] + self.ValueTwo[CurrentPeriod] + self.ValueThree[CurrentPeriod]
        self.TotalSumOfValues += self.SumOfValues[CurrentPeriod]

        self.HelperSumValueFour += self.ValueFour[CurrentPeriod]
        self.HelperSumValueTwo += self.AmountValueTwo[CurrentPeriod]
        self.HelperSumValueFive += self.ValueFive[CurrentPeriod]

        self.RatioOne[CurrentPeriod] = (1 - (self.HelperSumValueFour / self.HelperSumValueFive )) if self.HelperSumValueFive > 0 else 1
        self.RatioTwo[CurrentPeriod] = (1 - (self.HelperSumValueTwo  / self.HelperSumValueFive )) if self.HelperSumValueFive > 0 else 1

Tags: selfif时间else速度valuetwovalueonevaluethree
2条回答

代码看起来足够基本,在没有实质性重组的情况下没有任何明显的优化差距(我对您的总体架构了解不够,无法提出建议)。你知道吗

试着安装^{}——我相信现在你可以用pip install cython来安装它——然后用它来看看你是否可以加快代码的速度。你知道吗

如注释中所述,函数非常简单,使用提供的代码,我看不到直接优化它的方法。你知道吗

您可以尝试不同的方法:

  1. PyPy,这可能会根据您当前的代码库和外部依赖项而起作用。你知道吗
  2. Cython正如holdenweb所建议的,但是您需要重新定义许多静态类型的内容(使用cdef),否则什么都不会改变。你知道吗
  3. 将C中的函数重写为Python extension,这可能需要一些时间,尤其是在没有C编程经验的情况下。你知道吗

PyPy方法似乎是最合理的,如果它起作用,您将获得所有模拟代码的提升。你知道吗

相关问题 更多 >