Created
December 9, 2015 15:59
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
> 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note that the custom environment is needed to assign into, as a variable in the global environment will not get updated.