A
Size: a a a
A
АО
A
julia> const funs2 = (x -> x^2, x -> x^3)
julia> @code_warntype ntuple(i -> funs2[i](1), Val(2))
Variables
#self#::Core.Compiler.Const(ntuple, false)
f::Core.Compiler.Const(var"#43#44"(), false)
#unused#::Core.Compiler.Const(Val{2}(), false)
Body::Tuple{Int64,Int64}
1 ─ nothing
│ %2 = (f)(1)::Core.Compiler.Const(1, false)
│ %3 = (f)(2)::Core.Compiler.Const(1, false)
│ %4 = Core.tuple(%2, %3)::Core.Compiler.Const((1, 1), false)
└── return %4
A
АО
A
A
function ntuple(f::F, n::Integer) where F
t = n == 0 ? () :
n == 1 ? (f(1),) :
n == 2 ? (f(1), f(2)) :
n == 3 ? (f(1), f(2), f(3)) :
n == 4 ? (f(1), f(2), f(3), f(4)) :
n == 5 ? (f(1), f(2), f(3), f(4), f(5)) :
n == 6 ? (f(1), f(2), f(3), f(4), f(5), f(6)) :
n == 7 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7)) :
n == 8 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8)) :
n == 9 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9)) :
n == 10 ? (f(1), f(2), f(3), f(4), f(5), f(6), f(7), f(8), f(9), f(10)) :
_ntuple(f, n)
return t
end
A
VG
A
A
function _ntuple(f, n)
@_noinline_meta
(n >= 0) || throw(ArgumentError(string("tuple length should be ≥ 0, got ", n)))
([f(i) for i = 1:n]...,)
end
VG
const y = x->sin(x)
@time t = ntuple(y, Val(10)) # 0.000001 seconds (1 allocation: 96 bytes)
@time t = ntuple(y, Val(11)) # 0.000001 seconds (1 allocation: 96 bytes)
@time t = ntuple(y, 10) # 0.000001 seconds (1 allocation: 96 bytes)
@time t = ntuple(y, 11) # 0.000011 seconds (15 allocations: 512 bytes)
VG
VG
A
ntuple(f, ::Val{0}) = ()
ntuple(f, ::Val{1}) = (@_inline_meta; (f(1),))
ntuple(f, ::Val{2}) = (@_inline_meta; (f(1), f(2)))
ntuple(f, ::Val{3}) = (@_inline_meta; (f(1), f(2), f(3)))
@inline function ntuple(f::F, ::Val{N}) where {F,N}
N::Int
(N >= 0) || throw(ArgumentError(string("tuple length should be ≥ 0, got ", N)))
if @generated
quote
@nexprs $N i -> t_i = f(i)
@ncall $N tuple t
end
else
Tuple(f(i) for i = 1:N)
end
endVG
if @generated- проверяет, смог ли сгенерировать код?
A
A
АО