Created
July 27, 2022 19:47
-
-
Save aviatesk/42778d94e0b389a81e65c956d08c7c66 to your computer and use it in GitHub Desktop.
Check opaque closure invocation performance
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
import Core: MethodMatch | |
import Core.Compiler: _methods_by_ftype, InferenceParams, get_world_counter, MethodInstance, | |
specialize_method, InferenceResult, typeinf, InferenceState, NativeInterpreter, | |
code_cache | |
function custominvoke(f, args...) | |
@nospecialize f args | |
interp = NativeInterpreter() | |
tt = Base.signature_type(f, Tuple{map(Core.Typeof, args)...}) | |
mm = get_single_method_match(tt, InferenceParams(interp).MAX_METHODS, get_world_counter(interp)) | |
mi = specialize_method(mm.method, mm.spec_types, mm.sparams)::MethodInstance | |
code = Core.Compiler.get(code_cache(interp), mi, nothing) | |
if code !== nothing | |
inf = code.inferred::Vector{UInt8} | |
ci = Base._uncompressed_ir(code, inf) | |
return Core.OpaqueClosure(ci) | |
end | |
result = InferenceResult(mi) | |
frame = InferenceState(result, #=cache=# :global, interp) | |
typeinf(interp, frame) | |
ci = frame.src | |
return Core.OpaqueClosure(ci) | |
end | |
function get_single_method_match(@nospecialize(tt), lim, world) | |
mms = _methods_by_ftype(tt, lim, world) | |
isa(mms, Bool) && single_match_error(tt) | |
local mm = nothing | |
for i = 1:length(mms) | |
mmᵢ = mms[i]::MethodMatch | |
if tt === mmᵢ.spec_types | |
mm === nothing || single_match_error(tt) | |
mm = mmᵢ | |
end | |
end | |
mm isa MethodMatch || single_match_error(tt) | |
return mm | |
end | |
using Test, BenchmarkTools | |
@test sin(42) == custominvoke(sin, 42)(42) | |
@eval f(a) = $(custominvoke(sin, 42))(a) | |
g(a) = invokelatest(sin, a) | |
h(a) = sin(a) | |
@btime f(42) | |
@btime g(42) | |
@btime h(42) |
Author
aviatesk
commented
Jul 27, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment