Performance issues in simulation with python lists
<p>I'm currently writing a simulation in python 3.4 (miniconda).
The entire simulation is quite fast but the measurement of some simulation data is bloody slow and takes about 35% of the entire simulation time. I hope I can increase the performance of the entire simulation if I could get rid of that bottleneck. I spend quite some time to figure out how to do that but unfortunately with little success. The function MeasureValues is called in every period of the simulation run.</p>

<p>If anybody has an idea how to improve the code, I would be really grateful.</p>

<p>Thank you guys.</p>

<pre><code>def MeasureValues(self, CurrentPeriod):
    if CurrentPeriod &gt; self.WarmUp:
        self.ValueOne[CurrentPeriod] = self.FixedValueOne if self.Futurevalue[CurrentPeriod + self.Reload] &gt; 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 &gt; 0 else 1
        self.RatioTwo[CurrentPeriod] = (1 - (self.HelperSumValueTwo  / self.HelperSumValueFive )) if self.HelperSumValueFive &gt; 0 else 1
</code></pre>

<p>As stated in the comments the function is quite simple, and with the provided code I don't see a way to change optimize it directly.</p>

<p>You can try different approaches:</p>

<ol>
<li><a href="http://pypy.org/" rel="nofollow">PyPy</a>, this may works depending on your current codebase and external dependecies.</li>
<li><a href="http://cython.org/" rel="nofollow">Cython</a> as suggested by <em>holdenweb</em>, but you need to redefine a lot of stuff to be static-typed (using <code>cdef</code>) or nothing will change.</li>
<li>rewrite the function in C as a <a href="https://docs.python.org/3/extending/extending.html" rel="nofollow">Python extension</a>, this may take some time, especially if you have no experience in C programming.</li>
</ol>

<p>The <code>PyPy</code> way seems the most reasonable, if it works you will gain a boost for all the simulations code.</p>

python performance list python-3.x simulation