Please ignore this, post, the benchmark was wrong because I likely forgot to add -O3
when compiling the fortran code.
I will add some information here for Fortran programmers and, if anyone with a deeper knowledge of the inner workings of the compilers can correct something, please do.
Let us consider this simple function:
function loop(x,n)
s = 0.
for i in 1:n
r = sqrt(i)
s = s + x*r
end
s
end
Which would have the equivalent Fortran code:
double precision function loop(x,n)
implicit none
integer :: i, n
double precision :: x, r
loop = 0.
do i = 1, n
r = dsqrt(dble(i))
loop = loop + x*r
end do
end function loop
From the perspective of this thread, the difference is that the variable r
in the Julia code is only known locally at each iteration of the loop, while, at least from a synthatic point of view (I won’t speculate on what the compiler actually does), the variable is visible everywhere in the Fortran function.
The fact that the r
variable is visible only locally in the Julia loop allows further compiler optimizations than in the Fortran code, apparently. Effectively, the benchmark of these functions if very favorable to the to Julia version:
julia> x = rand() ; n = 10_000_000;
julia> @btime loop($x,$n)
15.039 ms (0 allocations: 0 bytes)
6.425913494015874e9
julia> @btime ccall((:loop_,"loop.so"),Float64,(Ref{Float64},Ref{Int64}),$x,$n)
87.733 ms (0 allocations: 0 bytes)
6.425913494015874e9
(the overhead of calling is negligible, and that is easy to test using a small n
)
The Fortran version was compiled with:
gfortran -O3 loop.f90 -shared -o loop.so
Evidently that a different compiler could perhaps figure out that r
does not need to be visible outside the loop and do a better job in the compilation of the Fortran code. But, in general, the more restricted scope of variables in Julia allows a better performance than the naive translations of the equivalent codes in Fortran.
At least this is has been my experience and these scoping differences are the only reason I can imagine to explain those performance advantages of Julia.