朱莉娅皮近似慢 [英] Julia pi approximation slow
问题描述
我的pi近似代码非常类似于官方页面上的代码:
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
当我尝试比较C和Julia的时间时,Julia的速度明显变慢,对于m = 100000000,C的时间几乎为38秒(C的时间为0.1608328933秒).为什么会这样?
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?
推荐答案
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)
我想从
避免全局变量全局变量可能具有其值,并且
因此,它的类型随时随地变化.这使得很难
编译器使用全局变量来优化代码.变量应
本地化,或尽可能将其作为参数传递给函数.....
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..... 宏 @code_warntype (或其函数变体code_warntype())可以
有时有助于诊断与类型相关的问题. The macro @code_warntype (or its function variant code_warntype()) can
sometimes be helpful in diagnosing type-related problems.
从 It's clear from 编辑 @ user3662120指出,答案的超快速行为是错误的结果,没有返回值LLVM可能会忽略for循环,通过添加返回行, 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 这篇关于朱莉娅皮近似慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
julia> @code_warntype piaprox();
Variables:
sum::Any
#s1::Any
i::Any
@code_warntype
输出清楚可见,编译器无法识别piaprox()
中的局部变量类型.因此,我们尝试声明类型并删除全局变量:@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
@time
结果将是:@time
result would be: julia> @time piaprox(100000000)
0.746795 seconds (11.11 k allocations: 400.294 KB, 0.45% gc time)
1.644934057834575