macros - Julia: inject code into function -
i inject code function. concreteness, consider simple simulater:
function simulation(a, x) t in 1:1000 z = randn(3) x = a*x + z end end sometimes record values of x every ten time-steps, values of z every 20 time-steps, , don't want record values. could, of course, put flags arguments function, , have if-else statements. rather keep simulation code clean, , inject piece of code like
if t%10 == 0 append!(rec_z, z) end into particular places of function whenever need it. that, i'd write macro such monitoring particular value becomes
@monitor(:z, 10) simulation(a, x) is possible julia's metaprogramming capabilities?
no, cannot use metaprogramming inject code already-written function. metaprogramming can things directly write @ precisely location macro written. means statement like:
@monitor(:z, 10); simulation(a, x) cannot modify simulation(a, x) function call. can expand out normal julia code runs before simulation called. could, perhaps, include simulation function call argument macro, e.g., @monitor(:z, 10, simulation(a, x)), macro can change function call itself. still cannot "go back" , add new code function written.
you could, however, , meticulously craft macro takes function definition body , modifies add debug code, e.g.,
@monitor(:z, 10, function simulation(a, x) t in 1:1000 # ... end end) but must write code in macro traverses code in function body, , injects debug statement @ correct place. not easy task. , it's harder write in robust manner wouldn't break moment modified actual simulation code.
traversing code , inserting easier task editor. common idiom debugging statements use one-liner, this:
const debug = false function simulation (a, x) t in 1:1000 z = rand(3) x = a*x + z debug && t%10==0 && append!(rec_z, z) end end what's cool here marking debug constant, julia able optimize away debugging code when it's false — doesn't appear in generated code! there no overhead when you're not debugging. mean, however, have restart julia (or reload module it's in) change debug flag. when debug isn't marked const, cannot measure overhead simple loop. , chances are, loop more complicated one. don't worry performance here until double-check it's having effect.
Comments
Post a Comment