| 1 |
#' Memory profiling R |
| 2 |
#' |
| 3 |
#' `profmem()` evaluates and memory profiles an \R expression. |
| 4 |
#' |
| 5 |
#' @param expr An \R expression to be evaluated and profiled. |
| 6 |
#' |
| 7 |
#' @param envir The environment in which the expression should be evaluated. |
| 8 |
#' |
| 9 |
#' @param substitute Should `expr` be [base::substitute()]:d or not. |
| 10 |
#' |
| 11 |
#' @param threshold The smallest memory allocation (in bytes) to log. |
| 12 |
#' |
| 13 |
#' @param on_error (character) Controls whether evaluation errors should |
| 14 |
#' signal an error (`"error"`), a warning (`"warning"), or be ignored |
| 15 |
#' (`"ignore"`; default). |
| 16 |
#' |
| 17 |
#' @return `profmem()` and `profmem_end()` returns the collected allocation |
| 18 |
#' data as an `Rprofmem` data.frame with additional attributes set. |
| 19 |
#' An `Rprofmem` data.frame has columns `what`, `bytes`, and `trace`, with: |
| 20 |
#' |
| 21 |
#' * `what`: (character) type of memory event; |
| 22 |
#' either `"alloc"` or `"new page"` |
| 23 |
#' * `bytes`: (numeric) number of bytes allocated or `NA_real_` |
| 24 |
#' (when `what` is `"new page"`) |
| 25 |
#' * `trace`: (list of character vectors) zero or more function names |
| 26 |
#' |
| 27 |
#' The attributes set are: |
| 28 |
#' |
| 29 |
#' * `threshold` : The threshold used (= argument `threshold`) |
| 30 |
#' * `expression`: The expression profiled (= argument `expr`) |
| 31 |
#' * `value` : The value of the evaluated expression |
| 32 |
#' (only set if there was no error) |
| 33 |
#' * `error` : The error object in case the evaluation failed |
| 34 |
#' (only set if there was an error) |
| 35 |
#' |
| 36 |
#' @details |
| 37 |
#' In order for memory profiling to work, \R must have been _built_ with memory |
| 38 |
#' profiling enabled. Function |
| 39 |
#' \code{\link[base:capabilities]{base::capabilities("profmem")}} will |
| 40 |
#' return `TRUE` of it is enabled, otherwise `FALSE`. |
| 41 |
#' If memory profiling is _not_ supported, `profmem()` and `profmem_begin()` |
| 42 |
#' will produce an informative error. The pre-built \R binaries on |
| 43 |
#' [CRAN](https://cran.r-project.org/) support memory profiling. |
| 44 |
#' |
| 45 |
#' What is logged? The `profmem()` function uses [utils::Rprofmem()] for |
| 46 |
#' logging memory, which logs all memory _allocations_ that are done via the |
| 47 |
#' \R framework. Specifically, the logger is tied to `allocVector3()` part |
| 48 |
#' of \R's native API. This means that nearly all memory allocations done |
| 49 |
#' in \R are logged. _Neither_ memory deallocations _nor_ garbage collection |
| 50 |
#' events are logged. Furthermore, allocations done by non-\R native libraries |
| 51 |
#' or \R packages that use native code `Calloc() / Free()` for internal objects |
| 52 |
#' are also _not_ logged. |
| 53 |
#' |
| 54 |
#' Any memory events that would occur due to calling any of the \pkg{profmem} |
| 55 |
#' functions themselves will _not_ be logged and _not_ be part of the returned |
| 56 |
#' profile data (regardless whether memory profiling is active or not). |
| 57 |
#' This is intentional. |
| 58 |
#' |
| 59 |
#' If a profmem profiling is already active, `profmem()` and `profmem_begin()` |
| 60 |
#' performs an _independent_, _nested_ profiling, which does not affect the |
| 61 |
#' already active one. When the active one completes, it will contain all |
| 62 |
#' memory events also collected by the nested profiling as if the nested one |
| 63 |
#' never occurred. |
| 64 |
#' |
| 65 |
#' Profiling gathered by \pkg{profmem} _will_ be corrupted if the code profiled |
| 66 |
#' calls [utils::Rprofmem()], with the exception of such calls done via the |
| 67 |
#' \pkg{profmem} package itself. |
| 68 |
#' |
| 69 |
#' |
| 70 |
#' @example incl/profmem.R |
| 71 |
#' |
| 72 |
#' @export |
| 73 |
#' @importFrom utils Rprofmem |
| 74 |
profmem <- function(expr, envir = parent.frame(), substitute = TRUE, threshold = getOption("profmem.threshold", 0L), on_error = c("ignore", "warning", "error")) { |
| 75 |
if (substitute) expr <- substitute(expr) |
| 76 |
on_error <- match.arg(on_error, choices = c("ignore", "warning", "error")) |
| 77 |
|
| 78 |
profmem_begin(threshold = threshold) |
| 79 |
|
| 80 |
## Profile memory |
| 81 |
error <- NULL |
| 82 |
value <- tryCatch({ |
| 83 |
eval(expr, envir=envir, enclos = baseenv()) |
| 84 |
}, error = function(ex) { |
| 85 |
error <<- ex |
| 86 |
NULL |
| 87 |
}) |
| 88 |
|
| 89 |
pm <- profmem_end() |
| 90 |
|
| 91 |
if (on_error != "ignore") { |
| 92 |
action <- switch(on_error, error = stop, warning = warning) |
| 93 |
action(paste("profmem::profmem() detected a run-time error:", |
| 94 |
conditionMessage(error))) |
| 95 |
} |
| 96 |
|
| 97 |
## Annotate |
| 98 |
attr(pm, "expression") <- expr |
| 99 |
attr(pm, "value") <- value |
| 100 |
attr(pm, "error") <- error |
| 101 |
|
| 102 |
pm |
| 103 |
} ## profmem() |
| 104 |
|
| 105 |
|
| 106 |
#' Memory profiling R |
| 107 |
#' |
| 108 |
#' `profmem_begin()` starts the memory profiling of all the following \R |
| 109 |
#' evaluations until `profmem_end()` is called. |
| 110 |
#' |
| 111 |
#' @return `profmem_begin()` returns (invisibly) the number of nested profmem |
| 112 |
#' session currently active. |
| 113 |
#' |
| 114 |
#' @rdname profmem |
| 115 |
#' @export |
| 116 |
profmem_begin <- function(threshold = getOption("profmem.threshold", 0L)) { |
| 117 |
## Is memory profiling supported? |
| 118 |
if (!capableOfProfmem()) { |
| 119 |
msg <- "Profiling of memory allocations is not supported on this R system (capabilities('profmem') reports FALSE). See help('tracemem')." |
| 120 |
if (.Platform$OS.type == "unix") { |
| 121 |
msg <- paste(msg, "To enable memory profiling for R on Linux, R needs to be configured and built using './configure --enable-memory-profiling'.") |
| 122 |
} |
| 123 |
stop(msg) |
| 124 |
} |
| 125 |
|
| 126 |
threshold <- as.integer(threshold) |
| 127 |
stop_if_not(length(threshold) == 1, is.finite(threshold), threshold >= 0L) |
| 128 |
|
| 129 |
depth <- profmem_stack("depth") |
| 130 |
if (depth > 0) { |
| 131 |
threshold_parent <- profmem_stack("threshold") |
| 132 |
if (threshold > threshold_parent) { |
| 133 |
warning(sprintf("Nested profmem threshold (%d bytes) cannot be greater than the threshold (%d bytes) of active profmem sessions (n = %d). Will use the active threshold instead.", threshold, threshold_parent, depth)) |
| 134 |
threshold <- threshold_parent |
| 135 |
} |
| 136 |
} |
| 137 |
|
| 138 |
profmem_suspend() |
| 139 |
|
| 140 |
## Push new level |
| 141 |
depth <- profmem_stack("push", threshold = threshold) |
| 142 |
|
| 143 |
profmem_resume() |
| 144 |
|
| 145 |
invisible(depth) |
| 146 |
} |
| 147 |
|
| 148 |
#' @rdname profmem |
| 149 |
#' @export |
| 150 |
profmem_end <- function() { |
| 151 |
profmem_suspend() |
| 152 |
|
| 153 |
depth <- profmem_stack("depth") |
| 154 |
if (depth == 0) { |
| 155 |
stop("Did you forget to call profmem_begin()?") |
| 156 |
} |
| 157 |
|
| 158 |
data <- profmem_stack("pop") |
| 159 |
|
| 160 |
profmem_resume() |
| 161 |
|
| 162 |
data |
| 163 |
} |
| 164 |
|
| 165 |
#' `profmem_suspend()` suspends an active profiling until resumed by |
| 166 |
#' `profmem_resume()` or ended by `profmem_end()`. |
| 167 |
#' Calling `profmem_begin()` or `profmem()` will resume any suspended |
| 168 |
#' profiling. _Nested_ resuming and suspending is _not_ supported; |
| 169 |
#' it is a global state. |
| 170 |
#' |
| 171 |
#' @return `profmem_suspend()` and `profmem_resume()` returns nothing. |
| 172 |
#' |
| 173 |
#' @rdname profmem |
| 174 |
#' @importFrom utils Rprofmem |
| 175 |
#' @export |
| 176 |
profmem_suspend <- function() { |
| 177 |
## Works regardless of active Rprofmem exists or not |
| 178 |
Rprofmem("") |
| 179 |
|
| 180 |
profmem_stack("suspend") |
| 181 |
|
| 182 |
## Nothing more to do? |
| 183 |
if (profmem_stack("depth") == 0) return() |
| 184 |
|
| 185 |
## Import current log |
| 186 |
drop <- length(sys.calls()) + 4L |
| 187 |
pathname <- profmem_pathname() |
| 188 |
data <- readRprofmem(pathname, drop = drop) |
| 189 |
attr(data, "threshold") <- profmem_stack("threshold") |
| 190 |
profmem_stack("append", data) |
| 191 |
|
| 192 |
invisible() |
| 193 |
} |
| 194 |
|
| 195 |
#' @rdname profmem |
| 196 |
#' @importFrom utils Rprofmem |
| 197 |
#' @export |
| 198 |
profmem_resume <- function() { |
| 199 |
threshold <- profmem_stack("threshold") |
| 200 |
pathname <- profmem_pathname() |
| 201 |
Rprofmem(filename = pathname, threshold = threshold) |
| 202 |
profmem_stack("resume") |
| 203 |
invisible() |
| 204 |
} |
| 205 |
|
| 206 |
|
| 207 |
#' `profmem_status()` checks whether there is an active profmem session |
| 208 |
#' or not, and whether it is suspended or not. |
| 209 |
#' |
| 210 |
#' @return `profmem_status()` returns `"inactive"`, `"active"`, |
| 211 |
#' or `"suspended"`. |
| 212 |
#' |
| 213 |
#' @rdname profmem |
| 214 |
#' @export |
| 215 |
profmem_status <- function() { |
| 216 |
profmem_stack("status") |
| 217 |
} |
| 218 |
|
| 219 |
#' `profmem_depth()` gets the number of nested / stacked profmem sessions. |
| 220 |
#' |
| 221 |
#' @return `promem_depth()` returns a non-negative integer. |
| 222 |
#' |
| 223 |
#' @rdname profmem |
| 224 |
#' @export |
| 225 |
profmem_depth <- function() { |
| 226 |
profmem_stack("depth") |
| 227 |
} |
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
profmem_pathname <- local({ |
| 232 |
pathname <- NULL |
| 233 |
function() { |
| 234 |
if (!is.null(pathname)) return(pathname) |
| 235 |
pathname <<- tempfile(pattern = "profmem.", fileext = ".Rprofmem.out") |
| 236 |
pathname |
| 237 |
} |
| 238 |
}) |
| 239 |
|
| 240 |
profmem_stack <- local({ |
| 241 |
empty <- data.frame(what = NULL, bytes = NULL, trace = NULL, stringsAsFactors = FALSE) |
| 242 |
empty <- structure(empty, class = c("Rprofmem", "data.frame"), threshold = 0L) |
| 243 |
|
| 244 |
stack <- list() |
| 245 |
suspended <- FALSE |
| 246 |
|
| 247 |
function(action = c("status", "depth", "threshold", "push", "pop", "append", "suspend", "resume"), |
| 248 |
data = empty, threshold = 0L) { |
| 249 |
action <- match.arg(action) |
| 250 |
|
| 251 |
## Status queries |
| 252 |
if (action == "status") { |
| 253 |
if (length(stack) == 0) return("inactive") |
| 254 |
if (suspended) return("suspended") |
| 255 |
return("active") |
| 256 |
} else if (action == "depth") { |
| 257 |
return(length(stack)) |
| 258 |
} else if (action == "threshold") { |
| 259 |
if (length(stack) == 0) return(NA_integer_) |
| 260 |
threshold <- attr(stack[[1]], "threshold") |
| 261 |
return(threshold) |
| 262 |
} |
| 263 |
|
| 264 |
## State changing |
| 265 |
if (action == "suspend") { |
| 266 |
suspended <<- TRUE |
| 267 |
## WORKAROUND: If not, above won't happen /2018-01-29 |
| 268 |
dummy <- suspended |
| 269 |
return(invisible(suspended)) |
| 270 |
} else if (action == "resume") { |
| 271 |
suspended <<- FALSE |
| 272 |
## WORKAROUND: If not, above won't happen /2018-01-29 |
| 273 |
dummy <- suspended |
| 274 |
return(invisible(suspended)) |
| 275 |
} |
| 276 |
|
| 277 |
|
| 278 |
## Stack changing |
| 279 |
if (action == "push") { |
| 280 |
stop_if_not(inherits(data, "Rprofmem"), |
| 281 |
length(threshold) == 1, is.finite(threshold), |
| 282 |
is.integer(threshold), threshold >= 0L) |
| 283 |
attr(data, "threshold") <- threshold |
| 284 |
stack <<- c(stack, list(data)) |
| 285 |
# message("PUSH: stack depth: ", length(stack)) |
| 286 |
return(length(stack)) |
| 287 |
} else if (action == "pop") { |
| 288 |
depth <- length(stack) |
| 289 |
if (depth == 0) stop("Cannot 'pop' - profmem stack is empty") |
| 290 |
value <- stack[[depth]] |
| 291 |
stack <<- stack[-depth] |
| 292 |
depth <- length(stack) |
| 293 |
if (depth >= 1) { |
| 294 |
tmp <- stack[[depth]] |
| 295 |
tmp <- if (is.null(tmp)) value else c(tmp, value) |
| 296 |
stack[[depth]] <<- tmp |
| 297 |
} |
| 298 |
# message("POP: stack depth: ", length(stack)) |
| 299 |
return(value) |
| 300 |
} else if (action == "append") { |
| 301 |
depth <- length(stack) |
| 302 |
if (depth == 0) stop("Cannot 'append' - profmem stack is empty") |
| 303 |
stop_if_not(inherits(data, "Rprofmem"), |
| 304 |
length(threshold) == 1, is.finite(threshold), |
| 305 |
is.integer(threshold), threshold >= 0L) |
| 306 |
attr(data, "threshold") <- threshold |
| 307 |
value <- stack[[depth]] |
| 308 |
value <- if (is.null(value)) data else c(value, data) |
| 309 |
stack[[depth]] <<- value |
| 310 |
# message("APPEND: stack depth: ", length(stack)) |
| 311 |
return(invisible(value)) |
| 312 |
} |
| 313 |
} |
| 314 |
}) |
| 315 |
|
| 316 |
|
| 317 |
|
| 318 |
### TODO: |
| 319 |
### |
| 320 |
### profmem_add_string <- function(msg, ...) { |
| 321 |
### pathname <- profmem_pathname() |
| 322 |
### cat(msg, file = pathname, append = file_test("-f", pathname)) |
| 323 |
### } |
| 324 |
### |
| 325 |
### ## FIXME: This produces lots of extra memory allocations, which |
| 326 |
### ## we don't want to inject. |
| 327 |
### profmem_add_note <- function(..., timestamp = TRUE) { |
| 328 |
### msg <- sprintf(...) |
| 329 |
### if (timestamp) { |
| 330 |
### msg <- sprintf("[%s] %s", format(Sys.time(), "%Y%m%d-%H%M%S"), msg) |
| 331 |
### } |
| 332 |
### msg <- sprintf("# %s\n", msg) |
| 333 |
### profmem_add_string(msg) |
| 334 |
### } |
| 335 |
|