For-loops and vectorized operations in Julia and R
After seeing a lot of posts recently, I downloaded and tried out Julia, described by its creators as a “high-level, high-performance dynamic programming language for technical computing”. I am interested in comparing to Rcpp/inline packages as well, which I have had good experience with, and which offer all the comforts of the R environment (reading, writing, plotting).
Here are my examples for a purposely slow for-loop and a vectorized form in R:
########################################
picalc <- function(n) {
z <- numeric(n)
for (i in 1:n) {
x <- runif(2)
if (sum(x^2) < 1) z[i] <- 4
}
mean(z)
}
picalcvec <- function(n) {
x <- runif(n)
y <- runif(n)
4 * sum(x^2 + y^2 < 1) / n
}
print("for loop")
picalc(1e6)
system.time({picalc(1e6)})
print("vectorized")
picalcvec(1e7)
system.time({picalcvec(1e7)})
########################################
.
.
.
and in Julia:
.
.
.
########################################
function picalc(n)
z = zeros(n)
for i = 1:n
x = rand(2)
if (sum(x .* x) < 1)
z[i] = 4
end
end
mean(z)
end
function picalcvec(n)
x = rand(n)
y = rand(n)
4 * sum(x .* x + y .* y < 1) / n
end
println("for loop")
println(picalc(int64(1e6)))
println(@elapsed picalc(int64(1e6)))
println("vectorized")
println(picalcvec(int64(1e7)))
println(@elapsed picalcvec(int64(1e7)))
########################################
.
.
.
On my laptop, Julia is much faster for the for-loop, 0.6 seconds compared to over 10 seconds with R. The vectorized function is about twice as fast. There were some issues with the pow(x,y) function, and the random functions are not fully built out yet. It’s an interesting start though, and it looks like they have cherry-picked the better syntax from MATLAB, python and R.
.
.
.
> R --no-save --slave < picalc.R [1] "for loop" [1] 3.141172 user system elapsed 10.396 0.120 10.713 [1] "vectorized" [1] 3.141377 user system elapsed 0.949 0.037 1.022 > julia picalc.jl for loop 3.144904 0.6278369426727295 vectorized 3.1420856 0.46157312393188477
leave a comment