Skip to content

Instantly share code, notes, and snippets.

@ScottPJones
Created November 1, 2015 14:48
Show Gist options
  • Select an option

  • Save ScottPJones/6f15de663e310faa5e2e to your computer and use it in GitHub Desktop.

Select an option

Save ScottPJones/6f15de663e310faa5e2e to your computer and use it in GitHub Desktop.
benchmark different abs versions
function checked_abs{T<:Signed}(x::T)
x == typemin(T) && throw(OverflowError())
abs(x)
end
function scott_abs{T<:Signed}(x::T)
(v = abs(x)) < 0 && throw(OverflowError())
v
end
function testnoop(n)
local v::Int
local i::Int
for i = -n:n
v = i
end
v
end
function testabs(n)
local v::Int
local i::Int
for i = -n:n
v = abs(i)
end
v
end
function testca(n)
local v::Int
local i::Int
for i = -n:n
v = checked_abs(i)
end
v
end
function testsa(n)
local v::Int
local i::Int
for i = -n:n
v = scott_abs(i)
end
v
end
# make sure they get compiled
@time testnoop(1)
@time testabs(1)
@time testca(1)
@time testsa(1)
# Run for real
println("v = i")
gc() ; gc() ; @time testnoop(1000000)
println("v = abs(i)")
gc() ; gc() ; @time testabs(1000000)
println("v = scott_abs(i)")
gc() ; gc() ; @time testsa(1000000)
println("v = checked_abs(i)")
gc() ; gc() ; @time testca(1000000)
# Show actual generated code
if false
@code_native(abs(-1))
@code_native(checked_abs(-1))
@code_native(scott_abs(-1))
end
# Where are these macros defined?
#Pkg.add("Benchmark")
#using Benchmarks
#@benchmark abs(-1)
#@benchmark checked_abs(-1)
#@benchmark scott_abs(-1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment