struct AwaredGenFn{F} # F是你的生成函数
end
function (agf::AwaredGenFn{F})(args...) where F
F(Val(Base.get_world_counter()), args...)
end
function (agf::AwaredGenFn{F})(args...; kwargs...) where F
F(Val(Base.get_world_counter()), args...; kwargs...)
end
macro awaredgenerated(ex)
quote
$AwaredGenFn{($Base.@generated $ex)}()
end |> esc
end
案例: 数量级提速subtypes
using InteractiveUtils
using BenchmarkTools
my_subtypes = @awaredgenerated function x(world, ::Type{T}) where T
subtypes(T)
end
@info my_subtypes(Number)
struct S <: Number end
@info my_subtypes(Number)
@btime my_subtypes(Number)
@btime subtypes(Number)
[ Info: Any[Complex, Real]
[ Info: Any[Complex, Real, S]
3.321 μs (1 allocation: 16 bytes)
4.688 ms (1044 allocations: 601.17 KiB)