I’m writing a stochastic simulation sofware in Julia.
I need to store expressions in strings, because I want to save them in a spreadsheet or database, due to the ease of change, without having to directly change source files in Julia.
The normal solution is
Eval, but this feature it’s painfully slow.
A test that I did using
time() function with
eval() in my real code was around 900x slower than native user defined functions.
It would be great a way to compile strings (more than
parse function does) in order to generate a compiled thunk (anonymous function)
Below I’ve coded a very simple demo for comparing
eval() and anonymous function
const iter = 1000000 const niter = 10000 function compiled() # use anonymous function local x::Float64 = 45 local i::Int64 local res::Float64 local ini::Float64 = time() local f::Function = () -> sind(x) for i = 1:iter res = f() end println("Compiled => Elapsed Time: ", @sprintf("%0.3f",(time()-ini)/iter * 1000000), " microseconds") end y = 45. function evaluated() # uses eval local i::Int64 local res::Float64 local ini::Float64 = time() local f::Expr = parse("sind(y)") for i = 1:niter res = eval(f) end println("Evaluated => Elapsed Time: ", @sprintf("%0.3f",(time()-ini)/niter * 1000000), " microseconds") end compiled() evaluated()
The results are amazing. 2950x faster!
Compiled => Elapsed Time: 0.020 microseconds
Evaluated => Elapsed Time: 59.000 microseconds
My syntax dream: In compiled() function replace
local f::Function = y -> sind(y)
local f::Function = compile("sind(y)")
Is there a hidden trick that I don’t get it?