Skip to content

Instantly share code, notes, and snippets.

@b-rodrigues
Created August 17, 2021 20:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save b-rodrigues/2b42b1e5bdf6b5637ab507c27c9cb2ab to your computer and use it in GitHub Desktop.
Save b-rodrigues/2b42b1e5bdf6b5637ab507c27c9cb2ab to your computer and use it in GitHub Desktop.
# Script to the video: https://youtu.be/erlWsquoHlM
set.seed(1234)
x <- abs(rnorm(1000))
in_base_R <- `^`(x, 2)
# code from https://helloacm.com/exponentiation-by-squaring/
fast_power <- function(base, power){
result <- 1
while(power > 0){
if(power %% 2 == 1){
result <- result * base
power <- power - 1
} else {
base <- base * base
power <- power / 2
}
}
result
}
benchmark <- microbenchmark::microbenchmark(
`^`(x, 2),
fast_power(x, 2)
)
benchmark
boxplot(benchmark)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment