Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia pi approximation slow

Tags:

julia

I have pi approximation code very similar to that on official page:

function piaprox()
    sum = 1.0
    for i = 2:m-1
        sum = sum + (1.0/(i*i))
    end
end

m = parse(Int,ARGS[1])
opak = parse(Int,ARGS[2])

@time for i = 0:opak
    piaprox()
end

When I try to compare time of C and Julia, then Julia is significantly slower, almost 38 sec for m = 100000000 (time of C is 0.1608328933 sec). Why this is happening?

like image 380
pavelf Avatar asked Dec 11 '22 17:12

pavelf


1 Answers

julia> m=100000000 
julia> function piaprox()
           sum = 1.0
           for i = 2:m-1
               sum = sum + (1.0/(i*i))
           end
       end
piaprox (generic function with 1 method)

julia> @time piaprox()
 28.482094 seconds (600.00 M allocations: 10.431 GB, 3.28% gc time)

I would like to mention two very important paragraphs from Performance Tips section of julia documentation:

Avoid global variables A global variable might have its value, and therefore its type, change at any point. This makes it difficult for the compiler to optimize code using global variables. Variables should be local, or passed as arguments to functions, whenever possible.....

The macro @code_warntype (or its function variant code_warntype()) can sometimes be helpful in diagnosing type-related problems.

julia> @code_warntype piaprox();
Variables:
  sum::Any
  #s1::Any
  i::Any

It's clear from @code_warntype output that compiler could not recognize types of local variables in piaprox(). So we try to declare types and remove global variables:

function piaprox(m::Int)
    sum::Float64 = 1.0
    i::Int = 0
    for i = 2:m-1
        sum = sum + (1.0/(i*i))
    end
end
julia> @time piaprox(100000000 )
  0.009023 seconds (11.10 k allocations: 399.769 KB)
julia> @code_warntype piaprox(100000000);
Variables:
  m::Int64
  sum::Float64
  i::Int64
  #s1::Int64

EDIT

as @user3662120 commented, the super fast behavior of the answer is result of a mistake, without a return value LLVM might ignore the for loop, by adding a return line the @time result would be:

julia> @time piaprox(100000000)
  0.746795 seconds (11.11 k allocations: 400.294 KB, 0.45% gc time)
1.644934057834575
like image 165
Reza Afzalan Avatar answered Dec 26 '22 11:12

Reza Afzalan