♣40♣The Need for Speed
In previous section, we focused on the issue where data becomes too large to be read into memory or causes the code to run too slowly. The first aspect – large data – is covered in the previous section, however, the reason why our code is slow, is not always due to data being too big. It might be related to the algorithm, the programming style, or we might have hit limits of what R naturally can do. In this section we will have a look on how to optimize code for speed – and assume that data-size is not the main blocking factor.
In this section we will show how we can evaluate and recognize efficient code and study various ways to speed up code. Most of those ways to reduce runtime are related to how R is implemented and what type of language it is. R is a high level interpreted language and provides complex data types with loads of functionalities and hides away much complexity. Using simpler data types, pre-allocating memory, and compiling code will therefore, be part of our basic toolbox.
40.1 Benchmarking
Before we start to look into details on optimizing for speed, we will need an objective way to tell if code is really faster or not. R has built-in tools to measure how long a function or code block runs via the function
system.time() of
base R, which we used before (for example in Chapter 37.3 “Using the GPU” on page 752).
We supply an expression to be timed to the function
system.time() as its argument.
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access