# Variable declaration and initialisation

**URL:** <https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923>\
**Category:** New to Julia\
**Created:** [October 15, 2019, 5:07am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923 "2019-10-15T05:07:26Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 15, 2019, 5:07am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/1 "2019-10-15T05:07:26Z")

</div>

I am trying to optimise a piece of my code. I have currently used `mutable struct` to declare variable types. Following which I assign values to them,

```julia
mutable struct Par
    N::Int64 ; 
    n::Int64 ; 
end
mutable struct Mat
    A::Array{Int64,2} ; 
    θₜ::Array{Float64,2} ; 
    Atemp::Array{Int64,2} ; 
    Asep::Array{Float64,2} ;
    allag::Array{Float64,2} ; 
end
p = Par(1000,5000) ;
m = Mat(zeros(Int64,p.N,p.N),zeros(Float64,p.n,p.N),zeros(Int64,p.N,p.N),zeros(Float64,p.N,p.N),zeros(Float64,p.N,p.N)) ;

```

I would want to increase values of `N` and `n` in subsequent simulations. But I notice already that initialising the matrices themselves take time of the order of 10^-3,

```julia
using BenchmarkTools
@btime m = Mat(zeros(Int64,p.N,p.N),zeros(Float64,p.n,p.N),zeros(Int64,p.N,p.N),zeros(Float64,p.N,p.N),zeros(Float64,p.N,p.N)) ;
  13.360 ms (21 allocations: 68.67 MiB)

```

Is there a faster/optimal way of doing this?

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [October 15, 2019, 5:09am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/2 "2019-10-15T05:09:59Z")

</div>

do you need to initialize different matrix of this size millions of times? (potentially you can use `Undef`) Looking at the allocation size, I think whatever you do you will be memory bounded.

---

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 15, 2019, 5:17am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/3 "2019-10-15T05:17:59Z")

</div>

I am carrying out MonteCarlo simulations, and I would like to increase `N` from 1000 to 100,000 or so. I was trying to see if I could save some time here to better the execution time.

---

<div class="post-metadata">

**Author:** ![PetrKryslUCSD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petrkryslucsd/32/215825_2.png) [@PetrKryslUCSD](https://discourse.julialang.org/u/PetrKryslUCSD)\
**Post date:** [October 15, 2019, 5:19am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/4 "2019-10-15T05:19:38Z")

</div>

I would try to design the algorithm to use a buffer pre-allocated, and reused over and over again.

---

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 15, 2019, 5:20am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/5 "2019-10-15T05:20:09Z")

</div>

Can you please suggest how to do so?

---

<div class="post-metadata">

**Author:** ![PetrKryslUCSD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petrkryslucsd/32/215825_2.png) [@PetrKryslUCSD](https://discourse.julialang.org/u/PetrKryslUCSD)\
**Post date:** [October 15, 2019, 5:37am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/6 "2019-10-15T05:37:19Z")

</div>

How about running the MC in parallel. Let us say in threads. Then each thread would have a buffer of the type you specified above, and when it starts it overwrites the values in the buffer with the correct initial values and takes off. This way you need to allocate only T thread buffers. Obviously, because each thread only accesses its own buffer, there is no memory race…And this way you don’t run out of memory when allocating lots of matrices that get used only once 🙂

---

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 15, 2019, 5:39am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/7 "2019-10-15T05:39:09Z")

</div>

Thank you. I am relatively new to Julia and not an ace programmer. Can I ask if there is any documentation on the use of threads, some example to look up to?

---

<div class="post-metadata">

**Author:** ![PetrKryslUCSD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petrkryslucsd/32/215825_2.png) [@PetrKryslUCSD](https://discourse.julialang.org/u/PetrKryslUCSD)\
**Post date:** [October 15, 2019, 6:14am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/8 "2019-10-15T06:14:40Z")

</div>

```julia
using Base.Threads
struct ThreadBuffer
	t::Int64
	parameters::Vector{Float64}
end

@show parameters = rand(10)
nth = 3
chunk = Int64(round(length(parameters) / nth))
buffers = ThreadBuffer[]
for t in 1:nth-1
	push!(buffers, ThreadBuffer(t, parameters[chunk*(t-1)+1:chunk*(t)+1-1]))
end
push!(buffers, ThreadBuffer(nth, parameters[chunk*(nth-1)+1:length(parameters)]))
@show buffers

threadwork(t) = begin
for p in 1:length(buffers[t].parameters)
	println("Thread $(t), Working with parameter = $(buffers[t].parameters[p])")
	sleep((nth-t+1)*rand())
end
end

tasks = []
Threads.@threads for t in 1:nth
	push!(tasks, Threads.@spawn threadwork(t))
end
for t in 1:length(tasks)
	Threads.wait(tasks[t])
end
println("Done")

```

---

<div class="post-metadata">

**Author:** ![non-Jedi](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/non-jedi/32/3645_2.png) [@non-Jedi](https://discourse.julialang.org/u/non-Jedi)\
**Post date:** [October 15, 2019, 8:13pm UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/9 "2019-10-15T20:13:58Z")

</div>

I’d strongly suggest getting the serial version of your code working  
before worrying about multi-threading. The only gotcha when moving  
from serial to parallel is making sure that any functions using random  
numbers take an rng as an argument rather than just using the global  
rng.

What we mean when we say use a pre-allocated buffer is just to do  
something like the following for memory of size `n*n` with `m`  
replications:

```julia
# Pre-allocate your matrix/vector/chunk of memory
mem = Matrix{Float64}(undef, n, n)
results = Vector{Float64}(undef, n)
for i in eachindex(results)
    for j in eachindex(mem)
        mem[j] = # do calculation
    end#for
    results[i] = f(mem)
end

```

Basically just re-use arrays you allocate as much as possible. If `n`  
varies between runs of your simulation, you can still re-use the  
arrays: just change them to the appropriate size with `resize!` (under  
the hood, julia may have to reallocate the array and copy its values  
to a different location in memory when `resize!`ing, but user-code  
doesn’t have to worry about that).

---

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 16, 2019, 5:13am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/10 "2019-10-16T05:13:02Z")

</div>

Thank you. I already have the [Serial version](https://github.com/NV2019/Julia/blob/master/git.jl) of my code working. Since, it takes really long, I am trying ways to optimise it and better the execution time. Any suggestions for doing the same will be of great help.

---

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 16, 2019, 7:21am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/11 "2019-10-16T07:21:34Z")

</div>

I was trying to understand what each syntax in this code does. When I tried running,

```julia
import Base.Threads.@spawn

```

```julia
Threads.@threads for t in 1:nth
	push!(tasks, Threads.@spawn threadwork(t))
end

```

I get the following errors,

```julia
WARNING: could not import Threads.@spawn into Main
UndefVarError: @spawn not defined

```

Is there something else that needs to be done?

---

<div class="post-metadata">

**Author:** ![PetrKryslUCSD](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/petrkryslucsd/32/215825_2.png) [@PetrKryslUCSD](https://discourse.julialang.org/u/PetrKryslUCSD)\
**Post date:** [October 16, 2019, 7:24am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/12 "2019-10-16T07:24:15Z")

</div>

> [@ennvvy](#):
>
> import Base.Threads.@spawn

Please remember to run this with Julia 1.3.

---

<div class="post-metadata">

**Author:** ![ennvvy](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/ennvvy/32/7816_2.png) [@ennvvy](https://discourse.julialang.org/u/ennvvy)\
**Post date:** [October 16, 2019, 7:47am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/13 "2019-10-16T07:47:53Z")

</div>

> [@PetrKryslUCSD](#):
>
> for t in 1:length(tasks) Threads.wait(tasks[t]) end

That worked. Thank you.

---

<div class="post-metadata">

**Author:** ![pablosanjose](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/pablosanjose/32/7006_2.png) [@pablosanjose](https://discourse.julialang.org/u/pablosanjose)\
**Post date:** [October 16, 2019, 8:25am UTC](https://discourse.julialang.org/t/variable-declaration-and-initialisation/29923/14 "2019-10-16T08:25:09Z")

</div>

If the post by @PetrKryslUCSD answered your question it is a good idea to mark it as “Solution”.
