Speeding up a function call inside a loop

loop over a very long container (millions elements) { each element compute 8 integers: k1,k2,k3,...,k8 call function func(k1,k2,k3,...,k8) } container is a std::vector, element is a long integer each k can only take {0,1,2,..5} six values. func is a simple expression of complex number calculation, involves std::conj and std::exp 

To speed things up, I cache all the possible results of the func function into an array and instead call func_array [k1] [k2] [k3] .... But if you just define func_array as: std :: complex func_array [6] [6] [ 6] ..., the program dies when the stack overflows.

Any better solutions to speed up?

0
source share
2 answers

If the func () function always returns the same value for a given set of inputs (for example, does not depend on time, depends on a sequence, etc.), you can do the following:

1. Whenever you call func (), save the result to the cache [using the values ​​k1 ... through k8 as the key to the cache entry]

2. Before calling func (), check if you have a cached value

The cache itself can be a Map, where you build the key by combining k1 ... thru ... k8 in some way, which is suitable for their data type.

0
source

You create an array std::complex[6][6]...[6] onto the stack? Firstly, this can lead to a stack overflow: this is a rather large array for many stacks. And second: if you create it on the stack, it will be reinitialized every time you call the function. You probably need a local static array that will be initialized once (the first time it occurs), and then store its value between function calls.

0
source

Source: https://habr.com/ru/post/948916/


All Articles