Skip to content

Instantly share code, notes, and snippets.

@greimel
Forked from anonymous/unpack-or-not-unpack.jl
Created January 31, 2018 15:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save greimel/1f50c5be866d010566ef480de74a18ef to your computer and use it in GitHub Desktop.
Save greimel/1f50c5be866d010566ef480de74a18ef to your computer and use it in GitHub Desktop.
Should we unpack in inner or outer function?
using Parameters
type Par{T <: Real}
α::T
β::T
end
### Implementation 1: unpack in outer function
function f1(x::T, y::T, α::T, β::T) where T <: Real
x^α * y^β
end
function g1(xx::Array{T}, yy::Array{T}, α::T, β::T) where T <: Real
mean(f1.(xx, yy, α, β))
end
function h1(n::Int, p::Par{Float64})
@unpack α, β = p
out = 0.0
for i in 1:n
xx = rand(500, 500)
yy = rand(500, 500)
out += g1(xx, yy, α, β)/n
end
end
### Implementation 2: unpack in inner function
function f2(x::T, y::T, p::Par{T}) where T <: Real
@unpack α, β = p
x^α * y^β
end
function g2(xx::Array{T}, yy::Array{T}, p::Par{T}) where T <: Real
mean(f2.(xx, yy, p))
end
function h2(n::Int, p::Par{Float64})
out = 0.0
for i in 1:n
xx = rand(500, 500)
yy = rand(500, 500)
out += g2(xx, yy, p)/n
end
end
xx = rand(100, 100)
yy = rand(100, 100)
p = Par(0.1, 0.2)
using BenchmarkTools
## compile on first run
h1(10, p)
h2(10, p)
## runs approximately 6 seconds each
gc()
@time h1(100, p)
gc()
@time h2(100, p)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment