# Mean function does not work in parallel calculations

**URL:** <https://discourse.julialang.org/t/mean-function-does-not-work-in-parallel-calculations/62685>\
**Category:** New to Julia\
**Created:** [June 10, 2021, 3:50pm UTC](https://discourse.julialang.org/t/mean-function-does-not-work-in-parallel-calculations/62685 "2021-06-10T15:50:16Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Beh123](https://avatars.discourse-cdn.com/v4/letter/b/13edae/32.png) [@Beh123](https://discourse.julialang.org/u/Beh123)\
**Post date:** [June 10, 2021, 3:50pm UTC](https://discourse.julialang.org/t/mean-function-does-not-work-in-parallel-calculations/62685/1 "2021-06-10T15:50:16Z")

</div>

hi, i want to calculate mean with @distributed. it is my code.

```julia
Using SharedArrays , Distributed , Statistics
addprocs(5)
@everywhere using SharedArrays
t=zeros(120,100,8)+zeros(120,100,8)*im 
s=convert(SharedArray,t)
function test()
@time @distributed for (i ,j) in collect(Iterators.product ( 1:100,1:8))
x=rand(200,120)+rand(200,120)*im 
y=rand(200,120)+rand(200,120)*im
z=x.*conj(y)
s[:,i , j]= (mean( z, dims=1))
end 
return s 
end
@time zz=test()
``
My result zz is zero why? When I remove @distributed of my code everything is OK. 
I need use @distributed to reach speed up.
```

---

<div class="post-metadata">

**Author:** ![oheil](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oheil/32/220745_2.png) [@oheil](https://discourse.julialang.org/u/oheil)\
**Post date:** [June 10, 2021, 8:06pm UTC](https://discourse.julialang.org/t/mean-function-does-not-work-in-parallel-calculations/62685/2 "2021-06-10T20:06:54Z")

</div>

Package Statistics needs to be used everywhere.  
(your code is a bit difficult to read and has some errors, so I repost it with the solution)

```julia
using Distributed
addprocs(5)

@everywhere using SharedArrays, Statistics

t=zeros(120,100,8)+zeros(120,100,8)*im 
s=convert(SharedArray,t)

function test()
	@time @distributed for (i ,j) in collect(Iterators.product( 1:100,1:8))
		x=rand(200,120)+rand(200,120)*im 
		y=rand(200,120)+rand(200,120)*im
		z=x.*conj(y)
		s[:,i , j]= (mean( z, dims=1))
	end 
	return s 
end

@time zz=test();

```

---

<div class="post-metadata">

**Author:** ![oheil](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/oheil/32/220745_2.png) [@oheil](https://discourse.julialang.org/u/oheil)\
**Post date:** [June 11, 2021, 3:04pm UTC](https://discourse.julialang.org/t/mean-function-does-not-work-in-parallel-calculations/62685/3 "2021-06-11T15:04:04Z")

</div>

~~Remark I forgot yesterday:  
But, if you do it like this, you will not get good performance result, because in the distributed case every worker has to do nearly the same work like before the single worker in the not distributed case. You distribute nearly the same workload as before on 5 workers so nearly quintupling the work.~~  
Wrong.
