Created
January 19, 2022 13:52
-
-
Save CnrLwlss/df03d500fc30c27e12818746c3005615 to your computer and use it in GitHub Desktop.
Parallel Julia code
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Multithreading is the most straightforward type of parallel processing supported by Julia | |
# https://docs.julialang.org/en/v1/manual/multi-threading/#man-multithreading | |
# If your parallel computing problem doesn't involve shared memory state | |
# then this is probably the way to go | |
Nthreads = Threads.nthreads(); | |
Ncalcs = Nthreads * 5 | |
# Let's distribute Ncalcs operations across Nthreads threads | |
# We can have a look at which thread carries out each operation | |
# Pre-allocate some memory for an array | |
a = zeros(Int,Ncalcs) | |
# Fill array using a thread-aware for loop | |
Threads.@threads for i = 1:(Ncalcs) | |
a[i] = Threads.threadid() | |
end | |
a | |
# More interesting/difficult problem is when each thread needs to access a common | |
# set of packages, functions and variables | |
# Let's try do some simulations from the discrete logistic map | |
# Logistic map iteration (definition) | |
function x_next(r::Real,x_previous::Real) | |
r*x_previous*(1.0-x_previous) | |
end | |
# Simulate from logistic map | |
function simulate(r::Real, x0::Real, Nsteps::Integer) | |
res = zeros(Nsteps+1) | |
res[1] = x0 | |
for i = 2:(Nsteps+1) | |
res[i] = x_next(r,res[i-1]) | |
end | |
return(res) | |
end | |
# Execute many logistic map simulations in parallel | |
function parsim(Nobs::Integer,Ncalcs::Integer) | |
output = Array{Float64, 2}(undef, Ncalcs, Nobs) | |
Threads.@threads for i = 0:(Ncalcs-1) | |
output[i+1,:] = simulate(3.7,i/(Ncalcs-1),Nobs-1) | |
end | |
return(output) | |
end | |
# Execute many logistic map simulations in serial | |
function singlesim(Nobs::Integer,Ncalcs::Integer) | |
output = Array{Float64, 2}(undef, Ncalcs, Nobs) | |
for i = 0:(Ncalcs-1) | |
output[i+1,:] = simulate(3.7,i/(Ncalcs-1),Nobs-1) | |
end | |
return(output) | |
end | |
# Compare simulation times | |
@time output_par = parsim(50000,10000); | |
@time output_single = singlesim(50000,10000); | |
#using Plots | |
#heatmap(output,cmap=:inferno) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment