Julia pi 逼近缓慢

标签 julia

我的 pi 近似代码与官方页面上的非常相似:

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

当我尝试比较 C 和 Julia 的时间时,Julia 明显更慢,m = 100000000 时几乎为 38 秒(C 的时间为 0.1608328933 秒)。为什么会发生这种情况?

最佳答案

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)

我想提一下 julia 文档 Performance Tips 部分中两个非常重要的段落:

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

@code_warntype 输出可以清楚地看出,编译器无法识别 piaprox() 中的局部变量类型。所以我们尝试声明类型并删除全局变量:
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

编辑

正如@user3662120 评论的那样,答案的超快行为是错误的结果,如果没有返回值,LLVM 可能会忽略 for 循环,通过添加返回行,@time 结果将是:
julia> @time piaprox(100000000)
  0.746795 seconds (11.11 k allocations: 400.294 KB, 0.45% gc time)
1.644934057834575

关于Julia pi 逼近缓慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36967443/

相关文章:

julia - 在 julia 中有效地求解特定的线性系统

julia - 如何将分区的 Apache Arrow 或 Parquet 文件读入/写出 Julia

julia - 是否有可能获得什么形式的联合类型的集合?

julia - 如何在 Julia 中使用 for 循环定义 JuMP 变量?

vim - 在 Vim 中为 Julia 突出显示语法的简单方法

julia - 类似于 'SubArray' 但有多个父数组?

dictionary - 删除 Julia 字典中重复的向量

optimization - Julia 相当于 python Continuous_groups() 函数

sorting - 定义自定义 sortperm 函数

arrays - 如何在 Julia 中连接不同大小的向量?