# Parallelizing a for-loop with a matrix

**URL:** <https://discourse.julialang.org/t/parallelizing-a-for-loop-with-a-matrix/62250>\
**Category:** Performance\
**Created:** [June 2, 2021, 5:51am UTC](https://discourse.julialang.org/t/parallelizing-a-for-loop-with-a-matrix/62250 "2021-06-02T05:51:22Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![natgeo-wong](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/natgeo-wong/32/10965_2.png) [@natgeo-wong](https://discourse.julialang.org/u/natgeo-wong)\
**Post date:** [June 2, 2021, 5:51am UTC](https://discourse.julialang.org/t/parallelizing-a-for-loop-with-a-matrix/62250/1 "2021-06-02T05:51:22Z")

</div>

I have a simple for-loop with a matrix, where I calculate a slice of the matrix via each step of the for-loop. e.g.

```julia
for ilat = 1 : nlat, ilon = 1 : nlon

    for ip = 1 : np; esat[ip+1] = t2esat(Ta[ilon,ilat,ip],p[ip+1]) end

    p[end] = ps[ilon,ilat]
    esat[end] = t2esat(Ts[ilon,ilat],p[end])
    swp[ilon,ilat,it] = calcswp(esat,p,ps[ilon,ilat])

end

```

I wish to parallelize the outer for-loop here. What packages should I use? Should I use `DistributedArrays`, or is `Distributed` enough? I’m not sure if I should use multi-threading, but I can use multiple cores. Do I need to specify the number of cores?

---

<div class="post-metadata">

**Author:** ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)\
**Post date:** [June 2, 2021, 5:56am UTC](https://discourse.julialang.org/t/parallelizing-a-for-loop-with-a-matrix/62250/2 "2021-06-02T05:56:28Z")

</div>

You might like

[https://juliafolds.github.io/data-parallelism/tutorials/quick-introduction/](https://juliafolds.github.io/data-parallelism/tutorials/quick-introduction/)

---

<div class="post-metadata">

**Author:** ![biona001](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/biona001/32/16497_2.png) [@biona001](https://discourse.julialang.org/u/biona001)\
**Post date:** [June 2, 2021, 7:00am UTC](https://discourse.julialang.org/t/parallelizing-a-for-loop-with-a-matrix/62250/3 "2021-06-02T07:00:50Z")

</div>

If you post runnable code (with inputs and maybe timings using [BenchmarkTools.jl](https://github.com/JuliaCI/BenchmarkTools.jl)), you’ll likely get much more response.

But in any case, I think you may want to start with multithreading by starting julia with `julia --threads 4` and adding `Threads.@threads` in front of your first for loop. `Distributed` is for distributed computing - when you have e.g. a cluster with multiple compute nodes.
