<p>我在一个类中的<strong>艰难的</strong>循环中使用<code>numpy.random.normal</code>函数。在</p>
<pre><code>class MyClass(MyBaseClass):
def run(self):
while True:
...
self.L.append(numpy.random.normal(0,1))
</code></pre>
<p>我知道在Python中使用多个查找非常慢。在<code>numpy.random.normal</code>中有3个查找:首先查找<code>numpy</code>,然后是<code>random</code>,然后是{<cd5>}。在</p>
<p>所以我决定通过将<code>numpy.random.normal</code>分配给一个局部变量<code>_normal</code>来解决这个问题。在</p>
<p>开始吧:</p>
^{pr2}$
<p>我真正关心的是描述词。当访问一个类中的一个变量时,所有基类都会查找同名的数据描述符。描述如下<a href="http://www.cafepy.com/article/python_attributes_and_methods/python_attributes_and_methods.html#attribute-search-summary" rel="nofollow">here</a>:</p>
<blockquote>
<p>Check <code>objectname.__class__.__dict__</code>for attrname. If it exists and is a data-descriptor, return the descriptor result. Search all bases of <code>objectname.__class__</code> for the same case.</p>
</blockquote>
<p>所以,我想,如果我像上面那样把<code>_normal</code>放在局部空间中,它将查找数据描述符的所有基类。我担心它会成为经济放缓的根源。在</p>
<p>我的担心有道理吗?在</p>
<p>我应该担心在基类中查找描述符所需的时间吗?在</p>
<p>在类中使用某个函数时,有没有更好的方法来加速对位于模块深处的函数的访问?在</p>
<hr/>
<p>在对答案的评论中进行了讨论。在</p>
<p>我决定提供一些似乎很重要的执行细节(对于我的特殊情况)。在</p>
<p>实际上,代码更接近于此(非常简化):</p>
<pre><code>class MyClass(MyBaseClass):
def __iter__(self):
return self
def next(self):
self.L.append(numpy.random.normal(0,1))
def run(self):
while True:
self.next()
</code></pre>
<blockquote>
<p>And I wary of it becoming a source of a slowdown.</p>
<p>Are my concerns justified?</p>
</blockquote>
<p>那要看情况了。对于你想要的应用程序,它已经足够快了吗?如果是这样,不要担心。CPython、PyPy、NumPy和moore定律的变化可能会在“减速”成为一个症结之前缓解它的严重程度。在</p>