I am using the numpy.random.normal
function in a hard loop in a class.
class MyClass(MyBaseClass): def run(self): while True: ... self.L.append(numpy.random.normal(0,1))
I know that in Python it's pretty slow to use multiple searches. There are 3 searches in numpy.random.normal
: numpy
looked at first, then random
, and then normal
.
So I decided to solve this problem by assigning numpy.random.normal
local variable _normal
.
Here we go:
class MyClass(MyBaseClass): _normal = numpy.random.normal def run(self): while True: ... self.L.append(MyClass._normal(0,1))
The descriptors really bother me. When a variable in a class is being accessed, all base classes look for a data descriptor with the same name. He described here :
Mark objectname.__class__.__dict__
for attrname. If it exists and is a data descriptor, return the result of the descriptor. Search all objectname.__class__
for the same case.
So, I suppose if I put _normal
in local space, as I said above, it will consider all the database classes for the data descriptor. And I fear that this will become a source of slowdown.
Are my concerns justified?
Do I have to worry about the time it takes to search for descriptors in base classes?
And is there a better way to speed up access to a function deep in a module when it is used in a class?
There was a discussion in the comments to the answers.
I decided to give some additional implementation details that turned out to be important (for my specific case).
Actually, the code is closer to this (it is very simplified):
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()