DAY 26
0

## 話說回來

``````x = rand(1000)
global y = rand(1000)

function sum_all()
s = 0.0
for i in x::Vector{Float64}
s += i
end
return s
end

function sum_all_global()
s = 0.0
for i in y::Vector{Float64}
s += i
end
return s
end

println("Test sum_all()")
@time sum_all()
println("Test sum_all_global()")
@time sum_all_global()
``````

``````function sum_all_with_para(x::Vector{Float64})
s = 0.0
for i in x
s += i
end
return s
end

function sum_all_global_with_para(y::Vector{Float64})
s = 0.0
for i in y
s += i
end
return s
end
``````

``````time_sum_all(x) = @time sum_all_with_para(x)
time_sum_all_global(x) = @time sum_all_global_with_para(x)

println("Test time_sum_all_with_para(x)")
time_sum_all(x)
println("Test time_sum_all_global_with_para(x)")
``````

• Avoid containers with abstract type parameters
• Avoid fields with abstract containers
• Annotate values taken from untyped locations
• Declare types of keyword arguments
• Break functions into multiple definitions (這也是阿杜提過的：善用multiple dispatch)
• Write "type-stable" functions
• Avoid changing the type of a variable
• Separate kernel functions (aka, function barriers)
• Types with values-as-parameters
..... 等

### 1 則留言

0

iT邦新手 5 級 ‧ 2018-10-27 22:24:43

``````x = rand(1000)

function sum_all()
s = 0.0
for i in x
s += i
end
return s
end

function sum_all_global()
s = 0.0
global x
for i in x
s += i
end
return s
end

println("Test sum_all(): ", @time sum_all())
println("Test sum_all_global(): ", @time sum_all_global())
``````