Often you will have working code, but simply want it to run faster.
In some cases it’s obvious where the bottle neck lies.
Sometimes you will guess, relying on intuition.
Sometime you're wrong
Rprof()
is a built-in tool for profiling the execution of R expressions.
At regular time intervals, the profiler stops the R interpreter, records the current function call stack, and saves the information to a file.
Stochastic
Each time we run a function R, the conditions have changed
Rprof()
is not user friendlylibrary("profvis") profvis({ data(movies, package = "ggplot2movies") # Load data movies = movies[movies$Comedy == 1, ] plot(movies$year, movies$rating) model = loess(rating ~ year, data = movies) # loess regression line j = order(movies$year) lines(movies$year[j], model$fitted[j]) # Add line to the plot })
In Monopoly moving around the board is complicated by the fact that rolling a double (a pair of 1's, 2's, ..., 6's) is special:
Roll two dice (total1): total_score = total1;
If you get a double, roll again (total2) and total_score = total1 + total2;
If you get a double, roll again (total3) and total_score = total1 + total2 + total3;
If roll three is a double, Go To Jail, otherwise move total_score.
## current is a value between 1 & 40 df = data.frame(d1 = sample(seq(1, 6), 3, replace = TRUE), d2 = sample(seq(1, 6), 3, replace = TRUE)) df$Total = apply(df, 1, sum) df$IsDouble = df$d1 == df$d2 if (df$IsDouble[1] & df$IsDouble[2] & df$IsDouble[3]) { current = 11#Go To Jail } else if (df$IsDouble[1] & df$IsDouble[2]) { current = current + sum(df$Total[1:3]) } else if (df$IsDouble[1]) { current = current + sum(df$Total[1:2]) } else { current = current + df$Total[1] }
However the code is (relatively) slow when we simulate the game multiple times
Using profvis()
can you pinpoint where this function is slow?
But, it runs too quickly for profvis()
, so
wrap the function in a loop
reduce the sampling interval, interval = 0.005
How would you speed it up?
vignette("profiling", package = "efficientTutorial")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.