Julia不同資料型別函式的內部程式碼比較

lt發表於2017-05-18

2個getg函式,一個未宣告引數型別.

julia> function getg(m)
         s=Int64(1);
         t=1;
         i=Int64(2);
         while t>0
           t=(s*10+1)%m
           i+=1;
           s=t;
         end
         i
       end
getg (generic function with 1 method)

julia> @time getg(10^8+7)
  2.033192 seconds (100.00 M allocations: 1.490 GB, 11.13% gc time)
100000007

julia> @time getg(10^9+7)
 20.931664 seconds (1000.00 M allocations: 14.901 GB, 11.95% gc time)
1000000007

julia> code_native(getg,(Any,))

一個引數型別為Int64

julia> function getg(m::Int64)
         s=Int64(1);
         t=Int64(1);
         i=Int64(2);
         while t>0
           t=(s*10+1)%m
           i+=1;
           s=t;
         end
         i
       end
getg (generic function with 2 methods)

julia> @time getg(Int64(10)^8+7)
  1.290397 seconds (6.87 k allocations: 140.112 KB)
100000007

julia> @time getg(Int64(10)^9+7)
 12.711004 seconds (7 allocations: 208 bytes)
1000000007

julia> code_native(getg,(Int64,))

沒指定型別的函式,原始碼2、3、5行有很多內容,執行消耗記憶體很多。指定的型別的函式都沒有2、3、5行的內容,消耗的記憶體也很少,速度快了1倍。

相關文章