Hi,
I'm trying to write better (faster) code in Julia, and here's an example
that I would like to understand where the difference in performance comes
from:
function test_1(μ,Δσ)
ub = int(μ+Δσ)
lb = int(μ-Δσ)
n_el = ub - lb
disc_dist = Array(Float64,n_el)
n = lb
for i = 1:n_el
disc_dist[i] = μ*σ*n
n += 1
end
# Return
return disc_dist
end
function test_2(μ,σ,x_σ)
ub = int(μ+x_σ*σ)
lb = int(μ-x_σ*σ)
n_el = ub - lb
disc_dist = Array(Float64,n_el)
n = lb
for i = 1:n_el
disc_dist[i] = μ*σ*n
n += 1
end
# Return
return disc_dist
end
function loop_states_1(n_states,μ,Δσ)
for i_state = 1:n_states
result = test_1(μ,Δσ)
end
end
function loop_states_2(n_states,μ,σ,x_σ)
for i_state = 1:n_states
result = test_2(μ,σ,x_σ)
end
end
# Parameters
σ = 4
μ = 22.3
x_σ = 2.0
Δσ = x_σ*σ
n_states = 500000
And then, when benchmarking:
@time test_1(μ,Δσ);
elapsed time: 2.4147e-5 seconds (1024 bytes allocated)
@time test_2(μ,σ,x_σ);
elapsed time: 1.382e-5 seconds (256 bytes allocated)
@time loop_states_1(n_states,μ,Δσ)
elapsed time: 1.598021522 seconds (472000096 bytes allocated, 32.01% gc time)
@time loop_states_2(n_states,μ,σ,x_σ)
elapsed time: 0.122917637 seconds (88000080 bytes allocated, 56.84% gc time)
The only difference between functions test_1 and test_2 is that the first one
takes as arguments (μ,Δσ) and the latter (μ,σ,x_σ).
Also the definitions for lb and ub. The output is the same. I've been reading
about type instability, annotations, ... but I can't see where the difference
in performance comes from.
Any help ?