Optimal way to speed up class method

Agree, I should indeed have put the specialisation into the __init__ given the specialisations are solely a function of variables at class instantiation.

Maybe each time mymethod is called on a new x there really is something compiled …

That’s exactly what’s happening, I wrote something too generalised! Given the per-class specialisation of the compiled code is solely down to values at initialisation time, redesigning this as you suggest prevents this from happening.

What you have in the above is probably about as good as it’ll get, but you can always add cache=True into the decorator to save having to compile new ones each time you run the code (presuming the values are the same). Think it’d also be ok to put the generator into the __init__ or as a @classmethod if desirable, e.g.

from numba import jit
import numpy as np

class MyClass(object):
    def __init__(self, a, b):
        self.a = a
        self.b = b
        self._method = self.generate(self.a, self.b)

    @classmethod
    def generate(cls, a, b):
        @jit(nopython=True, cache=True)
        def aux(x):
            #*do some complicated computations which involve a and b*
            return (a + b) * x # trivial example expression
        return aux

    def mymethod(self, x):
        return self._method(x)

inst = MyClass(0.1, 1.0)
print(inst.mymethod(2))

inst2 = MyClass(0.1, 2.0)
print(inst2.mymethod(2))

Anyway, glad you got something working! :slight_smile:

Also, there’s some general performance tips here that might be worth a read?