3 ms·
I decided to do some timing comparisons against the given R implementation on my system so that we have some numbers. The minimum time rw(1000000) takes in R is
by StefanKarpinski 12y ago
I decided to do some timing comparisons against the given R implementation on my system so that we have some numbers. The minimum time rw(1000000) takes in R is 0.02 seconds – sometimes it's 2x or 3x that, probably because GC kicks in. The vectorized Julia version above takes 0.01 seconds minimum – twice as fast as R – but often it's 2.5x slower than that, also because of GC. Here's a stab at what an obvious iterative random walk implementation might look like in Julia:
function rwi(n)
a = Array(Int,n)
s = 0
for i = 1:n
s += ifelse(randbool(), -1, 1)
a[i] = s
end
return a
end
rwi(1000000) takes 0.005 seconds. That's twice as fast as the vectorized Julia version and 4x faster than R. It also allocates much less memory than either one – just the output array. For 100000000 steps, R takes 2.717 seconds, the vectorized Julia version takes 1.52 seconds, and the iterative Julia version takes 0.6 seconds.