2.1 Profiling an R Workload Before Parallelizing It
Before you parallelize, measure. A parallel rewrite of a part that takes 5 percent of the run time can save at most that 5 percent, however many workers it gets.
2.1.1 Motivation
Parallelization spreads work across workers; it does not reduce the work, and it usually adds some. Each worker repeats setup, holds its own state, and pays to move data. Parallelization gains speed only when the part being parallelized takes enough of the run time to pay for that overhead.
Amdahl’s law formalizes this. If your serial bottleneck accounts for 10 percent of the runtime, parallelizing the remaining 90 percent with infinite workers yields at most a 10x speedup. If the bottleneck is 50 percent, you can gain at most 2x. The law sets the ceiling, and profiling tells you where the bottleneck is.
2.1.2 The profiling question
Profile to answer one question: what fraction of runtime can parallelization speed up? Everything else is noise. Suppose your pipeline spends 10 seconds in total, and 2 seconds inside a loop that runs once. Parallelizing that loop buys 20 percent at most. This is Amdahl’s law again, but the number matters more when it is your number.
2.1.3 Starting with elapsed time
Start with elapsed time. Run your workload once and measure wall-clock time. This is the time you experience. Write it down.
Now break it into parts. What fraction of elapsed time is R code executing? What fraction waits on I/O? What fraction does garbage collection consume? This breakdown tells you where to look next.
Use system.time() for this first pass. It is crude but fast.
An example
Assume you have a pipeline that takes 100 seconds end to end. system.time() reports three numbers: user is CPU time spent running R and your code, system is CPU time in the kernel, and elapsed is wall time. Say they come back as 80, 5 and 100. The CPU accounted for 85 of those 100 seconds, so 15 seconds went somewhere else.
Those 15 seconds went to waiting: on disk, on the network, or to be scheduled. Workers added for the compute leave that waiting where it is, unless the waits themselves can run side by side (several downloads at once, say).
One caveat on that subtraction. If your code calls into a multithreaded BLAS, user counts every thread’s CPU time and can exceed elapsed outright, which makes the residual negative and meaningless. Check whether native threads are running before you read anything into the gap.
2.1.4 CPU time versus elapsed time
Measure CPU time separately. CPU time is the sum of all processor cycles your code burns. Elapsed time is wall-clock time.
If CPU time and elapsed time are nearly identical, your workload is CPU-bound. Parallelization can help. Each worker consumes CPU. Adding workers increases total CPU throughput.
If elapsed time is much longer than CPU time, your workload is I/O-bound or blocking somewhere. The extra time comes from waiting on a network, a disk, or a lock. Parallelization helps only if the wait is on I/O and multiple workers can parallelize the I/O. If a single lock or connection serializes work, parallelization does not help.
2.1.5 R’s garbage collector as a bottleneck
R’s garbage collector writes to the header of every object it marks, so a collection is a write-heavy pass over the heap. Allocation pressure visible in the profiler often signals a tuning opportunity before parallelization is necessary.
If your profiler shows garbage collection taking 20 percent of the time, look at allocation before parallelization. Rprof(gc.profiling = TRUE) records which samples fell during a collection. A serial fix is faster to implement and easier to understand.
2.1.6 Profiling tools
R has several tools, each for a different purpose.
Rprof() samples the call stack at a fixed interval (20 ms by default) and records which functions were running. It samples CPU time by default on Unix-alikes and elapsed time on Windows; on Unix-alikes the event argument chooses, and Windows supports only elapsed time. summaryRprof() turns the samples into percentages per function. profvis visualizes the Rprof output and shows you flame graphs and memory allocations side by side.
For wall-clock measurement, system.time() is simplest. Wrap your code and run it. It shows user time, system time, and elapsed time.
For microbenchmarks, microbenchmark or the bench package time sub-millisecond operations. Both run an expression many times. microbenchmark prints the quartiles and bench keeps every timing for you to inspect, which suits small pieces of code. For a whole pipeline, a few system.time() runs tell you as much.
2.1.7 Separating concerns
A single profile number like “function F consumed 30 percent of time” tells you F is a candidate for optimizing. It does not tell you whether F can be parallelized, or whether the time is CPU, memory pressure, or I/O wait.
Read the profile. Look for functions with high CPU time that are also I/O-free. These are candidates for parallelization. Parallelizing an I/O-heavy function gains little. Read the source to understand what each function does.
Look for allocation patterns. Memory allocations that are proportional to input size often signal a tuning opportunity. Allocations inside a loop that runs thousands of times can often be optimized by allocating once and reusing.
2.1.8 When profiling is complete
Stop profiling when you can describe your workload in one sentence. For example: “This pipeline spends 40 percent in one call into compiled code that already uses every core, 30 percent in an R loop over independent samples, and 20 percent in garbage collection.” The loop is the candidate for parallel workers. The compiled call gains nothing from them, and garbage collection shrinks only if the code allocates less, since R’s collector runs on a single thread.
The goal of profiling is not a detailed breakdown. The goal is to find the serial bottleneck and to know whether that bottleneck can be parallelized. Profile until you know this much.
2.1.9 Profiling mistakes
A common mistake is profiling without knowing which time is being measured. Rprof() samples CPU time on Unix-alikes and elapsed time on Windows. An elapsed-time profile charges a function for the time it spends waiting on I/O, and a CPU-time profile does not. A function at 30 percent of an elapsed-time profile may be doing almost no CPU work, and parallelizing its computation will not help, because the time goes to the I/O it waits on.
Another mistake is profiling only one iteration of a workload. The first iteration includes startup costs that never happen again. JIT compilation, library loading, and cache warming all inflate the first run. If you care about throughput, profile multiple iterations together. If you care about startup latency specifically, profile the first iteration alone and say so.
A third mistake is profiling under atypical conditions. Profiling on a laptop with the browser open, email running, and background tasks spinning will show noise, not signal. Close everything. Run the workload alone on a quiet machine. Then the profile reflects your actual code, not your system state.
Worked profiling example
Assume you profile a pipeline:
Rprof()shows: 45 percent infit_model(), 30 percent intransform_data(), 15 percent in garbage collection, 10 percent in I/O.
Next: Read the source. fit_model() is a single lm() call on 10K rows. This is serial, not parallelizable. transform_data() applies a function row-wise. This is parallelizable.
Parallelizing transform_data() (30 percent) can pay off. Parallelizing fit_model() (45 percent) cannot, because it is a single call to a serial function.
Even so, parallelizing that 30 percent perfectly leaves the other 70 percent untouched, so the whole pipeline can get at most 1 / 0.70, about 1.43x. The serial remainder sets the ceiling, and no worker count moves it.
This is Amdahl’s law in practice.
2.1.10 Profile before optimizing: the golden rule
Profile before you optimize anything. Knuth made the point in 1974, on the same page as his line about premature optimization: “the universal experience of programmers who have been using measurement tools has been that their intuitive guesses fail.”
Without a profile, you optimize the wrong part of the program and waste effort. With a profile, you optimize the serial bottleneck and get real gains from parallelization. Profiling takes minutes; the wrong optimization can take days and deliver nothing.
2.1.11 The startup optimization trap
A common trap is optimizing startup before understanding whether startup matters. If your workload runs once a day for hours, a few seconds of startup are irrelevant. Optimize the steady-state work, not the startup cost. If your workload starts new processes constantly, startup cost matters. Then optimize it.
Profile to understand the distinction. Does startup dominate or not? Profile separately: the first run and the tenth run. If they are similar, startup does not matter. If the first run is much slower, it does. Then decide whether to optimize it based on how often that workload runs.
2.1.12 Reading a profile correctly
A profile is a histogram of where the sampled time went, function by function. Reading it correctly means:
- Find the function with the highest percentage.
- Look at its source code. Understand what it does.
- Determine whether it can be parallelized or optimized.
- Estimate the speedup (Amdahl’s law).
- Move to the next function.
Do not start optimizing until you have read the top five functions. Often you will find that the second or third function is more parallelizable than the first. Start with the highest impact, not the highest CPU time.
Profiling is not a one-time activity. Profile after each optimization to verify the change. The bottleneck shifts.
Further reading
RprofandsummaryRprof, the sampling profiler in base R. https://stat.ethz.ch/R-manual/R-devel/library/utils/html/Rprof.html- “Writing R Extensions”, section on tidying and profiling R code. https://cran.r-project.org/doc/manuals/r-release/R-exts.html#Tidying-and-profiling-R-code
- profvis, which renders
Rprof()output as an interactive flame graph. https://profvis.r-lib.org/ - Knuth, D. E. (1974). “Structured Programming with go to Statements”. ACM Computing Surveys 6(4), 261-301. The premature-optimization line comes from page 268 of this paper. It is not a separate essay. Read it in context: the surrounding argument is about when optimization is justified, not about avoiding it. https://doi.org/10.1145/356635.356640
- Lilja, D. J. (2000). Measuring Computer Performance: A Practitioner’s Guide. Cambridge University Press.