Created
August 27, 2015 11:38
-
-
Save cdsousa/9ae0e0b7c810a625d45e to your computer and use it in GitHub Desktop.
Experiments with literal vectors and matrices for FixedSizeArrays.jl
This file contains 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
using FixedSizeArrays: Mat, FixedVector | |
immutable Vec{N, T} <: FixedVector{N, T}; _::NTuple{N, T}; end | |
macro fsa(expr) | |
if expr.head == :vect | |
Expr(:call, :Vec, expr.args...) | |
elseif expr.head == :hcat | |
Expr(:call, :Mat, [Expr(:tuple, a) for a in expr.args]...) | |
elseif expr.head == :vcat | |
if isa(expr.args[1], Expr) && expr.args[1].head == :row | |
cols = [Any[] for _=1:length(expr.args[1].args)] | |
for row in expr.args | |
for (j, a) in enumerate(row.args) | |
push!(cols[j], a) | |
end | |
end | |
Expr(:call, :Mat, Expr(:tuple, [Expr(:tuple, col...) for col in cols]...)) | |
else | |
Expr(:call, :Vec, expr.args...) | |
end | |
end | |
end | |
begin | |
function test() | |
a = 1 | |
@assert @fsa([a,2,3]) == Vec(a,2,3) | |
@assert @fsa([a 2 3]) == Mat((a,),(2,),(3,)) | |
@assert @fsa([a;2;3]) == Mat(((a,2,3),)) | |
@assert @fsa([a 2;3 4]) == Mat(((a,3),(2,4))) | |
@assert @fsa([a 2 3;4 5 6]) == Mat(((a,4),(2,5),(3,6))) | |
@assert @fsa([a 2;3 4;5 6]) == Mat(((a,3,5),(2,4,6))) | |
end | |
test() | |
end | |
begin | |
function f1(a,b,c,d,e,f,g,h,i) | |
v = [a, b, c] | |
m = [a b c; d e f; g h i] | |
u = m*v | |
u[1], u[2], u[3] | |
end | |
function f2(a,b,c,d,e,f,g,h,i) | |
v = @fsa [a, b, c] | |
m = @fsa [a b c; d e f; g h i] | |
u = m*v | |
u[1], u[2], u[3] | |
end | |
function bench(n) | |
a,b,c,d,e,f,g,h,i = 1.,2.,3.,4.,5.,6.,7.,8.,9. | |
w,x,y,z = 0,0,0,0 | |
v1 = [a, b, c] | |
m1 = [a b c; d e f; g h i] | |
v2 = @fsa [a, b, c] | |
m2 = @fsa [a b c; d e f; g h i] | |
println("### Arrays ###") | |
@time for _=1:n; w = v1.*v1; end | |
@time for _=1:n; w = m1*v1; end | |
@time for _=1:n; x,y,z = f1(a,b,c,d,e,f,g,h,i); end | |
println("### FixedSizeArrays ###") | |
@time for _=1:n; w = v2.*v2; end | |
@time for _=1:n; w = m2*v2; end | |
@time for _=1:n; x,y,z = f2(a,b,c,d,e,f,g,h,i); end | |
end | |
println("_______________________________\n\n") | |
bench(1) | |
println("===============================\n\n") | |
bench(100000) | |
end | |
# ### Arrays ### | |
# 0.060454 seconds (800.04 k allocations: 33.572 MB, 3.44% gc time) | |
# 0.015885 seconds (200.00 k allocations: 10.681 MB, 9.60% gc time) | |
# 0.031641 seconds (1.70 M allocations: 54.932 MB, 6.89% gc time) | |
# ### FixedSizeArrays ### | |
# 0.000000 seconds | |
# 0.000387 seconds | |
# 0.000759 seconds |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment