I am trying to implement some “fixed stochasticity” in individual functions of my model (called once), where I have a global seed and then this is re-seed on each needed function based on the name of the function and the global seed, such that different functions are uncorrelated but the same function provides at each call the same outcomes, without passing RNGs around.
Anyhow, my issue is that in order to achieve this behaviour I need to use a non-const global (at module level) on the macro, and I wonder if this has a performance effect on the function calling the macro, or the macro implies a barrier effect.
This is a snippet of what I am trying to achieve:
cd(@__DIR__)
module Foo
import Random
export random_seed
global_random_seed = 123
macro random_seed!()
return quote
st = stacktrace(backtrace())
myf = ""
for frm in st
funcname = frm.func
if frm.func != :backtrace && frm.func!= Symbol("macro expansion")
myf = frm.func
break
end
end
m1 = $("$(__module__)")
s = m1 * "$(myf)"
Random.seed!(hash("$s",UInt64(global_random_seed)))
@info "Random seeded with hash of \"$s\" and $(global_random_seed)"
end
end
function init()
Foo.global_random_seed = parse(Int64,readline("test_seed.txt")) #just 125 in test_seed.txt
end
module FooFoo
import ..Foo
import ..Foo:@random_seed!, global_random_seed
function foo()
@random_seed!()
println(rand())
println(rand())
end
function goo()
@random_seed!()
println(rand())
println(rand())
end
end
end
Foo.init()
Foo.FooFoo.foo() # Julia v1.11: 0.008282138701719233 0.9042476148934772
Foo.FooFoo.foo() # Julia v1.11: 0.008282138701719233 0.9042476148934772
Foo.FooFoo.goo() # Julia v1.11: 0.4430332457748505 0.7426054431450675
Foo.FooFoo.goo() # Julia v1.11: 0.4430332457748505 0.7426054431450675
Foo.FooFoo.foo() # Julia v1.11: 0.008282138701719233 0.9042476148934772