11  Um bilhão

Teste de velocidade do cálculo da soma de 1 até 1 bilhão, a partir do R.

11.1 R

Código
library(tictoc)

sum_until_r <- function(numero = 10) {
    n <- 0
    while (n < numero) 
        n <- n + 1 
    n
}

tictoc::tic()
sum_until_r(1000000000)
tictoc::toc()

21.264 sec elapsed

11.2 Python from Reticulate

Código
library(reticulate) 

tictoc::tic()
py_run_string("
n = 0
while(n < 1000000000):
    n+=1

print(n)
")
tictoc::toc()

48.923 sec elapsed

11.3 Python

Código
# open python console in vim or rstudio 
# reticulate::repl_python()

import time

def sum_until_py(numero = 10):
    n = 0
    while(n < numero):
        n+=1
    return n

tic = time.perf_counter()
sum_until_py(1000000000)
toc = time.perf_counter()

print(toc - tic, 'secs')

25.6930 secs

11.4 Python source

code/um-bilhao/um-bilhao.py
import datetime

def sum_until_py(numero = 10):
    n = 0
    while(n < numero):
        n+=1
    return n
Código
reticulate::source_python('code/um-bilhao/um-bilhao.py')

tictoc::tic()
sum_until_py(1000000000)
tictoc::toc()

37.102 sec elapsed

11.5 Julia from JuliaCall

Código
library(JuliaCall) 
julia <- julia_setup()

julia_command("
function sum_until_jl(numero) 
i = 0
while i <= numero
    i += 1
end
end", show_value = F)

tictoc::tic()
julia_command("sum_until_jl(1000000000)")
tictoc::toc()

0.001 sec elapsed

11.6 Julia

Código
# open julia console in vim or rstudio 
# julia_console()

@time begin
njl = 0;
while njl <= 1000000000
    global njl += 1
end
end

272.569 seconds (1000.00 M allocations: 14.901 GiB, 0.15% gc time)

11.7 Julia source

code/um-bilhao/um-bilhao.jl
function sum_until_jl(numero = 1000) 
    i = 0 
    while i <= numero 
        i += 1 
    end 
    i
end
Código
julia_source('code/um-bilhao/um-bilhao.jl')

tictoc::tic()
julia_call('sum_until_jl', 1000000000)
tictoc::toc()

1.158 sec elapsed

11.8 C++ via Rcpp

Código
library(Rcpp)

cppFunction("
int sum_until_cpp(int numero) { 
    int n = 0; 
    while (n < numero)
        n++;
    return n;
}
")

tictoc::tic()
sum_until_cpp(1000000000)
tictoc::toc()

0.001 sec elapsed

11.9 C++ via Rcpp source

code/um-bilhao/um-bilhao.cpp
#include <Rcpp.h>
using namespace Rcpp ;

// [[Rcpp::export]]
int sum_until_v2_cpp(int numero) { 
    int n = 0; 
    while (n < numero)
        n++;
    return n;
}
Código
sourceCpp('code/um-bilhao/um-bilhao.cpp')

tictoc::tic()
sum_until_v2_cpp(1000000000)
tictoc::toc()

0.001 sec elapsed