Python Forum

Full Version: Memory access speed problem
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have to change a lot of values in a matrix by values that only change position where to act, but never change value.

For example:
|3 3 3|
|2 2 2|
|1 1 1|

has to result to

|4 4 4|
|4 4 4|
|4 4 4|

by summing

|1 1 1|
|2 2 2|
|3 3 3|

However, this one:
|5 5 5|
|5 5 5|
|5 5 5|

sums to (which is the previous sum swapped around in a deterministic way)
|3 3 3|
|1 1 1|
|2 2 2|

resulting

|8 8 8|
|6 6 6|
|7 7 7|


So, instead of calculating what to sum to each value (which basically means to recreate the entire matrix every time), I had the (seemingly terrible) idea of pre-creating a mask matrix and swap it around as it sums values:

|1 1 1| <-first starts here
|2 2 2|
|3 3 3| <-second starts here
|1 1 1|
|2 2 2|

However, calculating each individual value to sum has been shown at least 10x faster than using a swapped mask.
grid[j][i] += 1/(1.3*(1+math.sqrt(math.pow(x-j, 2) + math.pow(y-i, 2))))
is much, much, much faster than
grid[j][i] += (1./1.3)*harmonic_mask[x - j + grid_w][y - i + grid_h]
... Why?

(Consider tested: With the proper harmonic_mask, this math is correct. It is just much slower. The example mask is NOT an harmonic mask)