朱莉娅皮近似慢 [英] Julia pi approximation slow

查看:78
本文介绍了朱莉娅皮近似慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

@code_warntype输出清楚可见,编译器无法识别piaprox()中的局部变量类型.因此,我们尝试声明类型并删除全局变量:

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

编辑

@ user3662120指出,答案的超快速行为是错误的结果,没有返回值LLVM可能会忽略for循环,通过添加返回行,@time结果将是:

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

这篇关于朱莉娅皮近似慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆