Created
November 1, 2015 14:48
-
-
Save ScottPJones/6f15de663e310faa5e2e to your computer and use it in GitHub Desktop.
benchmark different abs versions
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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