Skip to content

Instantly share code, notes, and snippets.

@gghatano
Last active January 3, 2016 03:09
Show Gist options
  • Save gghatano/8400006 to your computer and use it in GitHub Desktop.
Save gghatano/8400006 to your computer and use it in GitHub Desktop.
R vs Cpp (sorting)
# R vs Cpp (sorting)
library(Rcpp)
library(inline)
library(ggplot2)
library(reshape2)
# sort_stl
src <- "
NumericVector x(xx);
std::sort(x.begin(), x.end());
return x;
"
stlsort <- cxxfunction(signature(xx="numeric"), src, plugin = "Rcpp")
# Cpp vs R (sorting)
Mmax <- 8
time_r <- numeric(Mmax)
time_stl <- numeric(Mmax)
for (M in 3:Mmax){
print(paste("loop = ", M))
N <- 10^M
random <- sample(1:N, N, replace=FALSE)
time_r[M] <- system.time(sort(random))[3]
time_stl[M] <- system.time(stlsort(random))[3]
}
# ggplot
time_data <- data.frame(R = time_r, Cpp = time_stl)
time_data <- melt(time_data)
size <- rep((1:8),2)
time_data$size <- 10^size
names(time_data) <- c("method", "time", "size")
library(scales)
p <- ggplot(data = time_data, aes(x=size, y=time, col=method))
p <- p + scale_x_log10()
p <- p + geom_line(size = 2) + geom_point(size=4)
p <- p + scale_x_log10(breaks=10^(1:8),
labels=trans_format("log10", math_format(10^.x)))
p <- p + ggtitle("R vs C++")
p <- p + theme(text=element_text(size=16))
p
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment