Debian Codegraph @

vignettes/profmem.md.rsp

raw
1 <%@meta language="R-vignette" content="--------------------------------
2 %\VignetteIndexEntry{Simple Memory Profiling for R}
3 %\VignetteAuthor{Henrik Bengtsson}
4 %\VignetteKeyword{R}
5 %\VignetteKeyword{package}
6 %\VignetteKeyword{vignette}
7 %\VignetteKeyword{memory}
8 %\VignetteKeyword{profiling}
9 %\VignetteKeyword{garbage collection}
10 %\VignetteKeyword{data type}
11 %\VignetteKeyword{coercion}
12 %\VignetteEngine{R.rsp::rsp}
13 %\VignetteTangle{FALSE}
14 --------------------------------------------------------------------"%>
15 <%
16 library("R.utils")
17
18 oopts <- options(
19 "withCapture/newline" = FALSE,
20 mc.cores = 2L,
21 digits = 2L
22 )
23 set.seed(0xBEEF) ## Just to minimize diff when rebuilt
24
25 ## WORKAROUND: Avoid spurious memory allocations that occurs
26 ## occasional when running in a fresh R session
27 options(profmem.threshold = 1000)
28
29 ## Initiate the random number generator, because otherwise it will
30 ## be done and captured during the first profiling below. It is not
31 ## fully clear to me what the R internals behind this is. For instance,
32 ## it is not enough to call `sample.int(n = 1)`. But calling rnorm(n = 1)
33 ## seems to avoid the problem.
34 rnorm(n=1)
35 %>
36
37 # Simple Memory Profiling in R
38
39 ## Introduction
40
41 The `profmem()` function of the [profmem] package provides an easy way to profile the memory usage of an R expression. It logs all memory allocations done in R. Profiling memory allocations is helpful when we, for instance, try to understand why a certain piece of R code consumes more memory than expected.
42
43 The `profmem()` function builds upon existing memory profiling features available in R. It logs _every_ memory allocation done by plain R code as well as those done by native code such as C and Fortran. For each entry, it records the size (in bytes) and the name of the functions on the call stack.
44 For example,
45
46 <% if (capabilities('profmem')) { %>
47 <% gc() %>
48 ```r
49 <%=withCapture({
50 library("profmem")
51 options(profmem.threshold = 2000)
52
53 p <- profmem({
54 x <- integer(1000)
55 Y <- matrix(rnorm(n = 10000), nrow = 100)
56 })
57 p
58 })%>
59 ```
60 <% p <- na.omit(p) %>
61 From this, we find that <%= p$bytes[1] %> bytes are allocated for integer vector `x`, which is because each integer value occupies 4 bytes of memory. The additional 40 bytes are due to the internal data structure used for each variable R. The size of this allocation can also be confirmed by the value of `object.size(x)`.
62 We also see that `rnorm()`, which is called via `matrix()`, allocates <%= p$bytes[2] %> bytes, which reflects the <%= length(Y) %> double values each occupying 8 bytes.
63 Finally, the following entry reflects the memory allocation of <%= tail(p$bytes, 1) %> bytes done by `matrix()` itself.
64 <% } else { %>
65
66 **WARNING: This vignette was compiled with an R version that was built with memory profiling disabled, cf. `capabilities('profmem')`. Please redo!**
67
68 <% } ## if (capabilities('profmem')) %>
69
70
71 ## An example where memory profiling can make a difference
72
73 Assume we want to set a 100-by-100 matrix with missing values except for element (1,1) that we assign to be zero. This can be done as:
74 ```r
75 <%=withCapture({
76 x <- matrix(nrow = 100, ncol = 100)
77 x[1, 1] <- 0
78 x[1:3, 1:3]
79 })%>
80 ```
81 This looks fairly innocent, but it turns out that it is very inefficient - both when it comes to memory and speed. The reason is that the default value used by `matrix()` is `NA`, which is of type _logical_. This means that initially `x` is a _logical_ matrix not a _numeric_ matrix. When we the assign the (1,1) element the value `0`, which is a _numeric_, the matrix first has to be coerced to _numeric_ internally and then the zero is assigned. Profiling the memory will reveal this;
82
83 <% if (capabilities('profmem')) { %>
84 <% gc() %>
85
86 ```r
87 <%=withCapture({
88 p <- profmem({
89 x <- matrix(nrow = 100, ncol = 100)
90 x[1, 1] <- 0
91 })
92 print(p, expr = FALSE)
93 })%>
94 ```
95 The first entry is for the logical matrix with 10,000 elements (= 4 \* 10,000 bytes + small header) that we allocate. The second entry reveals the coercion of this matrix to a numeric matrix (= 8 \* 10,000 elements + small header).
96
97 To avoid this, we make sure to create a numeric matrix upfront as:
98 ```r
99 <%=withCapture({
100 p <- profmem({
101 x <- matrix(NA_real_, nrow = 100, ncol = 100)
102 x[1, 1] <- 0
103 })
104 print(p, expr = FALSE)
105 })%>
106 ```
107
108 Using the [microbenchmark] package, we can also quantify the extra overhead in processing time that is introduced due to the logical-to-numeric coercion;
109 ```r
110 <%=withCapture({
111 library("microbenchmark")
112 stats <- microbenchmark(
113 bad = {
114 x <- matrix(nrow = 100, ncol = 100)
115 x[1, 1] <- 0
116 },
117 good = {
118 x <- matrix(NA_real_, nrow = 100, ncol = 100)
119 x[1, 1] <- 0
120 },
121 times = 100,
122 unit = "ms"
123 )
124 stats
125 })%>
126 ```
127 The inefficient approach is 1.5-2 times slower than the efficient one.
128
129
130 The above illustrates the value of profiling your R code's memory usage and thanks to `profmem()` we can compare the amount of memory allocated of two alternative implementations. Being able to write memory-efficient R code becomes particularly important when working with large data sets, where an inefficient implementation may even prevent us from performing an analysis because we end up running out of memory. Moreover, each memory allocation will eventually have to be deallocated and in R this is done automatically by the garbage collector, which runs in the background and recovers any blocks of memory that are allocated but no longer in use. Garbage collection takes time and therefore slows down the overall processing in R even further.
131
132 <% } else { %>
133
134 **WARNING: This vignette was compiled with an R version that was built with memory profiling disabled, cf. `capabilities('profmem')`. Please redo!**
135
136 <% } ## if (capabilities('profmem')) %>
137
138
139 ## What is logged?
140
141 The `profmem()` function uses the `utils::Rprofmem()` function for logging memory allocation events to a temporary file. The logged events are parsed and returned as an in-memory R object in a format that is convenient to work with. All memory allocations that are done via the native `allocVector3()` part of R's native API are logged, which means that nearly all memory allocations are logged. Any objects allocated this way are automatically deallocated by R's garbage collector at some point. Garbage collection events are _not_ logged by `profmem()`.
142 Allocations _not_ logged are those done by non-R native libraries or R packages that use native code `Calloc() / Free()` for internal objects. Such objects are _not_ handled by the R garbage collector.
143
144 ### Difference between `utils::Rprofmem()` and `utils::Rprof(memory.profiling = TRUE)`
145 In addition to `utils::Rprofmem()`, R also provides `utils::Rprof(memory.profiling = TRUE)`. Despite the close similarity of their names, they use completely different approaches for profiling the memory usage. As explained above, the former logs _all individual_ (`allocVector3()`) memory allocation whereas the latter probes the _total_ memory usage of R at regular time intervals. If memory is allocated and deallocated between two such probing time points, `utils::Rprof(memory.profiling = TRUE)` will not log that memory whereas `utils::Rprofmem()` will pick it up. On the other hand, with `utils::Rprofmem()` it is not possible to quantify the total memory _usage_ at a given time because it only logs _allocations_ and does therefore not reflect deallocations done by the garbage collector.
146
147
148 ## Requirements
149
150 In order for `profmem()` to work, R must have been built with memory profiling enabled. If not, `profmem()` will produce an error with an informative message. To manually check whether an R binary was built with this enable or not, do:
151 ```r
152 <%=withCapture({
153 capabilities('profmem')
154 })%>
155 ```
156 The overhead of running an R installation with memory profiling enabled compared to one without is neglectable / non-measurable.
157
158 Volunteers of the R Project provide and distribute pre-built binaries of the R software for all the major operating system via [CRAN]. [It has been confirmed](https://github.com/HenrikBengtsson/profmem/issues/2) that the R binaries for Windows, macOS (both by CRAN and by the AT&T Research Lab), and for Linux (\*) all have been built with memory profiling enabled. (\*) For Linux, this has been confirmed for the Debian/Ubuntu distribution but yet not for the other Linux distributions.
159
160
161 In all other cases, to enable memory profiling, which is _only_ needed if `capabilities("profmem")` returns `FALSE`, R needs to be _configured_ and _built from source_ using:
162 ```sh
163 $ ./configure --enable-memory-profiling
164 $ make
165 ```
166 For more information, please see the 'R Installation and Administration' documentation that comes with all R installations.
167
168
169
170 [CRAN]: https://cran.r-project.org/
171 [profmem]: https://cran.r-project.org/package=profmem
172 [microbenchmark]: https://cran.r-project.org/package=microbenchmark
173
174 ---
175 Copyright Henrik Bengtsson, 2016-2018
176
177 <%
178 ## Clean up
179 options(oopts)
180 %>