I tried the following codes, but the performance is very different among the codes. I heard that codes at the top level are not suitable for numerical calculations, but performance also seems to depend on whether the top level variables (here, N) appear in the for-loops range. Is it always best to avoid such top-level variables?
N = 10000000
x = 0.0
@time for k = 1:N
x += float( k )
end
@time let
y = 0.0
for j = 1:N
y += float( j )
end
end
@time let
n::Int64
n = N
z = 0.0
for m = 1:n
z += float( m )
end
end
function func1()
c = 0.0
for i = 1:N
c += float( i )
end
end
function func2( n )
c = 0.0
for i = 1:n
c += float( i )
end
end
function func3()
n::Int
n = N
c = 0.0
for i = 1:n
c += float( i )
end
end
function func4()
n = N
c = 0.0
for i = 1:n
c += float( i )
end
end
@time func1()
@time func2( N )
@time func3()
@time func4()
The result obtained using Julia 0.3.7 (on Linux x86_64),
elapsed time: 2.595440598 seconds (959985496 bytes allocated, 10.70% gc time)
elapsed time: 2.469471127 seconds (959983688 bytes allocated, 11.49% gc time)
elapsed time: 1.608e-6 seconds (16 bytes allocated)
elapsed time: 2.535243279 seconds (960021976 bytes allocated, 11.21% gc time)
elapsed time: 0.002601149 seconds (75592 bytes allocated)
elapsed time: 0.003471583 seconds (84456 bytes allocated)
elapsed time: 2.480343146 seconds (960020752 bytes allocated, 11.48% gc time)
source
share