Skip to content

Instantly share code, notes, and snippets.

@rmflight
Created December 9, 2015 15:59
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 rmflight/20f10db5c27b3623c321 to your computer and use it in GitHub Desktop.
Save rmflight/20f10db5c27b3623c321 to your computer and use it in GitHub Desktop.
reproducible example to get number of counts of function runs in semi-recursive
# function where first calls another function, that in turn calls the first,
# but does so in a way that the second is not called again. I want to test
# how many times f1 and f2 get called under different conditions
f1 <- function(use_f2 = FALSE){
if (use_f2) {
f2()
}
}
f2 <- function(){
f1(use_f2 = FALSE)
}
function_counts <- new.env()
function_counts$f1 <- function_counts$f2 <- 0
trace(f1, tracer = quote(function_counts$f1 <- function_counts$f1 + 1), print = FALSE)
trace(f2, tracer = quote(function_counts$f2 <- function_counts$f2 + 1), print = FALSE)
f1()
function_counts$f1
function_counts$f2
function_counts$f1 <- function_counts$f2 <- 0
f1(TRUE)
function_counts$f1
function_counts$f2
function_counts$f1 <- function_counts$f2 <- 0
f2()
function_counts$f1
function_counts$f2
> f1()
> function_counts$f1
[1] 1
> function_counts$f2
[1] 0
>
> function_counts$f1 <- function_counts$f2 <- 0
> f1(TRUE)
> function_counts$f1
[1] 2
> function_counts$f2
[1] 1
>
> function_counts$f1 <- function_counts$f2 <- 0
> f2()
> function_counts$f1
[1] 1
> function_counts$f2
[1] 1
@rmflight
Copy link
Author

rmflight commented Dec 9, 2015

Note that the custom environment is needed to assign into, as a variable in the global environment will not get updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment