Skip to content

Instantly share code, notes, and snippets.

@xukai92
Last active February 24, 2021 13:51
Show Gist options
  • Save xukai92/32a9098cc597f4ad10e8f5897e1eb09c to your computer and use it in GitHub Desktop.
Save xukai92/32a9098cc597f4ad10e8f5897e1eb09c to your computer and use it in GitHub Desktop.
`invokelatest` vs `mk_function`
using InteractiveUtils
versioninfo()
using DrWatson
@quickactivate
using Comonicon, Test, BenchmarkTools, ExprOptimization
using ExprOptimization.ProbabilisticExprRules: RuleNode, mindepth_map, ProbabilisticGrammar
using GeneralizedGenerated: mk_function
module GeneratedFunctions end
G = @grammar begin
Real = m1
Real = m2
Real = r²
Real = Real + Real
Real = Real - Real
Real = Real * Real
Real = Real / Real
end
PCFG = ProbabilisticGrammar(G)
# NOTE: This version fails due to the world age problem.
# function gen_f_invoke(tree)
# ex = get_executable(tree, G)
# f = eval(:((m1, m2, r²) -> $ex))
# return (m1, m2, r²) -> f(m1, m2, r²)
# end
function gen_f_invoke(tree)
ex = get_executable(tree, G)
f = eval(:((m1, m2, r²) -> $ex))
return (m1, m2, r²) -> Base.invokelatest(f, m1, m2, r²)
end
function gen_f_mkfunc(tree)
ex = get_executable(tree, G)
return mk_function(GeneratedFunctions, :((m1, m2, r²) -> $ex))
end
@main function main(N::Int, D::Int)
t = Dict(:invoke => zeros(N), :mkfunc => zeros(N))
Threads.@threads for i in 1:N
m1, m2, r² = rand(3)
tree = rand(RuleNode, PCFG, :Real, mindepth_map(G), D)
f_invoke = gen_f_invoke(tree)
f_mkfunc = gen_f_mkfunc(tree)
@test f_invoke(m1, m2, r²) == f_mkfunc(m1, m2, r²)
t[:invoke][i] = @belapsed $f_invoke($m1, $m2, $r²)
t[:mkfunc][i] = @belapsed $f_mkfunc($m1, $m2, $r²)
end
t = (invoke=sum(t[:invoke]), mkfunc=sum(t[:mkfunc]))
@info "Benchmark results for N=$N, D=$D" t...
end
"""```
┌ Info: Benchmark results for N=10, D=10
│ invoke = 1.250671490593281e-6
└ mkfunc = 5.58e-9
```"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment