在Julia中用明確的變數型別來優化

lt發表於2017-03-29

下面2個函式,一個函式用明確的變數型別,一個沒用,效能差別很大,分配記憶體差別也很大

julia> function f4(r::Int)
       sum1=Int64(0)
       for a in 1:r
       for b in 1:floor(Int64,sqrt(r^2 - a^2))
       for c in 1:floor(Int64,sqrt(r^2 - a^2 - b^2))
       sum1=sum1+floor(Int64,sqrt(r^2 - a^2 - b^2 - c^2))
       end end end
       sum1*16
       end
f4 (generic function with 1 method)

julia> @time f4(400)
  0.572900 seconds (5 allocations: 176 bytes)
125261529600

julia> function f4_1(r::Int)
       sum1=0
       for a in 1:r
       for b in 1:floor(Int64,sqrt(r^2 - a^2))
       for c in 1:floor(Int64,sqrt(r^2 - a^2 - b^2))
       sum1=sum1+floor(Int64,sqrt(r^2 - a^2 - b^2 - c^2))
       end end end
       sum1*16
       end
f4_1 (generic function with 1 method)

julia> @time f4_1(400)
  2.690156 seconds (66.65 M allocations: 1017.140 MiB, 3.51% gc time)
125261529600

相關文章