我的 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/