armando
armando

Reputation: 1480

why Julia code performance is much lower than Fortran one?

I read in several places that the performance of Julia code can (under certain conditions) be compared to the one of Fortran. I wrote the following code in Julia:

Pi = 3.141592653589793238462643
n = 100000 
function integration_2d(n,Pi,sum)
       h = Pi/n
       for i=1:n
           x = h*(i-0.5)
           for j=1:n
               y = h*(j-0.5)
               sum = sum + cos(x + y)
           end
       end
       sum*h*h
end

and the mean execution time was 180 sec. A Fortran code which has a very close structure than the one in Fortran compiled with -O3 option had an execution time of 0.013 sec. I wonder where the Julia code is losing performance, any comment is appreciated. Thanks.

Upvotes: 1

Views: 238

Answers (1)

Vitaliy Yakovchuk
Vitaliy Yakovchuk

Reputation: 493

Since you did not provide the Fortran code, I assume your code implemented differently with Fortran. Your O(N^2) algorithm requires CPU with > ~10^12 operations per seconds (even if to use Assembler), and I guess you did not use supercomputer for this test :). We could implement your algorithm in a way that requires O(N) performance. Julia code would look like that:

function integration_2d(n, sum=0.0)
    h = π / n
    multiplier = 1
    for i = 2:2n
        z = h * (i - 0.5)
        sum = sum + multiplier * cos(z)
        if i <= n
            multiplier += 1
        else
            multiplier -= 1
        end
    end
    sum * h * h
end

julia> @time integration_2d(100000)
  0.002846 seconds

Wich is 0.002846 seconds (> 4x times faster the the Fortran time you mantioned) on my laptop (since you did not provide your Fortran code I cannot properly compare performance on the same machine)

Upvotes: 5

Related Questions