Skip to content

Instantly share code, notes, and snippets.

@vsbuffalo
Created August 24, 2010 21: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 vsbuffalo/548414 to your computer and use it in GitHub Desktop.
Save vsbuffalo/548414 to your computer and use it in GitHub Desktop.
trace_calls.R
tracked <- new.env()
makeCounted <- function(fun, loud=FALSE) {
assign(fun, TRUE, envir=tracked)
calls <- 0
countedFun <- function(...) {
calls <<- .Primitive('+')(1, calls)
if (loud)
cat('call made to:', fun, '\n')
.Primitive(fun)(...)
}
return(countedFun)
}
getCounts <- function() {
tmp <- ls(envir=tracked)
counts <- cbind(sapply(tmp, function(x)
get('calls', envir=environment(get(x)))))
print(counts)
invisible(counts)
}
`[` <- makeCounted("[")
`[<-` <- makeCounted("[<-")
`+` <- makeCounted("+")
n <- 100
x <- rnorm(n)
y <- rnorm(n)
r <- numeric(n)
for (i in seq_along(x)) {
r[i] <- x[i] + y[i]
}
getCounts()
## Explicit calls
## for (i in seq_along(x)) {
## `[<-`(r, i, `+`(`[`(x, i), `[`(y, i)))
## }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment