Home > Software engineering >  python save computation power with repeatedly called functions
python save computation power with repeatedly called functions

Time:08-06

Let's say I have the following function, which takes x and y.

def calculate(x, y):
    return sin(x)**3   y

In my use case, I call the function very often but mainly change y and x only once in a while. Since my function is computationally intense I would like to speed it up. Of course, I could restructure the complete code so that nothing gets calculated multiple times, but the added speed would not justify the added complexity.

I recall there was something for exactly this but I cannot remember what it was (maybe functools or some decorator?).

CodePudding user response:

In order to save time and computation power, I recommend you use functools module.

The functools module is a cache module in python that gives you the ability to cache the result of your functions.

cache is a decorator that helps in reducing function execution for the same inputs using the memoization technique.

from functools import cache

@cache
def calculate(x, y):
    return sin(x)**3   y

CodePudding user response:

The cache decorator from functools is ideal for this. The caching mechanism is also known as memoization.

The implementation of a cache is straightforward. Think of it as a dictionary with keys constructed from the parameters passed to the function. Unless there's some kind of random component involved in the function implementation then the return value would be the same every time.

This means that by simply looking up the "key", the return value can be deduced without actually executing the function code.

Therefore:

from functools import cache
from math import sin

@cache
def calculate(x, y):
  return sin(x)**3   y

Don't be tempted to use this decorator for every function however. Consider this:

@cache
def calculate(x, y):
  return x   y

Of course, this works BUT there's a small overhead in terms of the cache implementation which, in this particular case, would mean that use of the cache actually slows down the response

  • Related