Fast way to Implement a Loop

Hello, I am beginning to use Julia and I want to ask for help doing something efficiently.

I am trying to compute a summation in Julia using the following loop.

`````` for (k_j,kk) = enumerate(k)
value=0
for (s_j,ss) = enumerate(s), (z_j,zz) = enumerate(z), (w_j,ww) = enumerate(w)
value=value+V₀[w_j,z_j,k_j,s_j]*H[s_i,s_j]*mat[w_j,w_i,z_j,z_i]*G[z_i,z_j]
end
end
``````

Which is basically calling over specific entries of matrices and adding them up. I’ve tried to make this faster and leaner with a reduce or mapreduce, but haven’t been able to get the code off the ground.

Any suggestion is appreciated, Thanks

Please provide a self-contained working example, which includes the variants you have tried and the way you are benchmarking them.

Hi!

There are two things that come to my mind:

1. Wrap your code in a function to allow precompilation and specialization on the types
(Just pass everything the function needs as arguments - not access global variables)
2. then write `value = 0.0` to make sure that your operation is type stable ( Otherwise it is first initialized as an `Int` and then converted to a `Float64`

If you would like more specific help, you would need to provide a (minimal) working self contained example,
so that we can just copy your code and it runs.

If you post a question in several fora, please provide a link to the other question:

3 Likes

Just to be clear here — the “fast” way to write a for loop is to write the three letters `for …`. There’s no magic. There’s no need to contort things to vectorize into a `mapreduce` (or some other) function call. Those functions you call? They just use a Julia `for` loop spelled with exactly the same three letters you write.

Julia’s for loops are fast, particularly if you follow the guidance here: https://docs.julialang.org/en/v1/manual/performance-tips/

1 Like