I’m making my first effort to move from Matlab to Julia and have found my code to improve by ~3x but still think there is more to come, I’m not using any global variables in the function and have preallocated all the arrays used (I think?). If there was any thoughts on how it could be sped up even further it would be greatly appreciated, I’ll fully convert even at the current improvement I think!
function word_sim(tau::Int, omega::Int, mu::Float64) # inserts a word in position (tau+1), at each point creates a new word with prob mu # otherwise randomly chooses a previously used. Runs the program until time omega words = zeros(Int32, 1, omega) # to store the words tests = rand(1,omega) # will compare mu to these words = 1; # initialize the words next_word = 2 # will be the next word used words[tau+1] = omega + 1; # max possible word so insert that at time tau innovates = mu .> tests; # when we'll make a new word for i = 2:tau # simulate the process if innovates[i] == 1 # innovate words[i] = next_word next_word = next_word + 1 else # copy words[i] = words[rand(1:(i-1))] end end # force the word we're interested in for i = (tau+2):omega if innovates[i] == 1 # innovate words[i] = next_word next_word = next_word + 1 else # copy words[i] = words[rand(1:(i-1))] end end result = sum(words .== (omega + 1)); # count how many times our word occurred return result end
and when I run it with these values it takes ~.26 seconds on my PC
using Statistics @time begin nsim = 10^3; omega = 100; seed = [0:1:(omega-1);]; mu = 0.01; results = zeros(Float64, 1, length(seed)); pops = zeros(Int64, 1, nsim); for tau in seed for jj = 1:nsim pops[jj] = word_sim(tau, omega, mu); end results[tau+1] = mean(pops); end end
Or perhaps I’d be better writing the code in C++? Julia was my first reaction as I’ve heard rave reviews about its syntax, which to be honest is fantastic!
Any comments greatly appreciated.