-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathStrategies-To-Improve-And-Speedup-R-Code.html
477 lines (440 loc) · 29.2 KB
/
Strategies-To-Improve-And-Speedup-R-Code.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<!DOCTYPE html>
<html>
<head>
<title>Strategies To Speedup R Code</title>
<meta charset="utf-8">
<meta name="Description" content="R Language Tutorials for Advanced Statistics">
<meta name="Keywords" content="R, Tutorial, Machine learning, Statistics, Data Mining, Analytics, Data science, Linear Regression, Logistic Regression, Time series, Forecasting">
<meta name="Distribution" content="Global">
<meta name="Author" content="Selva Prabhakaran">
<meta name="Robots" content="index, follow">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="shortcut icon" href="/screenshots/iconb-64.png" type="image/x-icon" />
<link href="www/bootstrap.min.css" rel="stylesheet">
<link href="www/highlight.css" rel="stylesheet">
<link href='http://fonts.googleapis.com/css?family=Inconsolata:400,700'
rel='stylesheet' type='text/css'>
<!-- Color Script -->
<style type="text/css">
a {
color: #3675C5;
color: rgb(25, 145, 248);
color: #4582ec;
color: #3F73D8;
}
li {
line-height: 1.65;
}
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
</style>
<!-- Add Google search -->
<script language="Javascript" type="text/javascript">
function my_search_google()
{
var query = document.getElementById("my-google-search").value;
window.open("http://google.com/search?q=" + query
+ "%20site:" + "http://r-statistics.co");
}
</script>
</head>
<body>
<div class="container">
<div class="masthead">
<!--
<ul class="nav nav-pills pull-right">
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
Table of contents<b class="caret"></b>
</a>
<ul class="dropdown-menu pull-right" role="menu">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</ul>
-->
<ul class="nav nav-pills pull-right">
<div class="input-group">
<form onsubmit="my_search_google()">
<input type="text" class="form-control" id="my-google-search" placeholder="Search..">
<form>
</div><!-- /input-group -->
</ul><!-- /.col-lg-6 -->
<h3 class="muted"><a href="/">r-statistics.co</a><small> by Selva Prabhakaran</small></h3>
<hr>
</div>
<div class="row">
<div class="col-xs-12 col-sm-3" id="nav">
<div class="well">
<li>
<ul class="list-unstyled">
<li class="dropdown-header"></li>
<li class="dropdown-header">Tutorial</li>
<li><a href="R-Tutorial.html">R Tutorial</a></li>
<li class="dropdown-header">ggplot2</li>
<li><a href="ggplot2-Tutorial-With-R.html">ggplot2 Short Tutorial</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part1-With-R-Code.html">ggplot2 Tutorial 1 - Intro</a></li>
<li><a href="Complete-Ggplot2-Tutorial-Part2-Customizing-Theme-With-R-Code.html">ggplot2 Tutorial 2 - Theme</a></li>
<li><a href="Top50-Ggplot2-Visualizations-MasterList-R-Code.html">ggplot2 Tutorial 3 - Masterlist</a></li>
<li><a href="ggplot2-cheatsheet.html">ggplot2 Quickref</a></li>
<li class="dropdown-header">Foundations</li>
<li><a href="Linear-Regression.html">Linear Regression</a></li>
<li><a href="Statistical-Tests-in-R.html">Statistical Tests</a></li>
<li><a href="Missing-Value-Treatment-With-R.html">Missing Value Treatment</a></li>
<li><a href="Outlier-Treatment-With-R.html">Outlier Analysis</a></li>
<li><a href="Variable-Selection-and-Importance-With-R.html">Feature Selection</a></li>
<li><a href="Model-Selection-in-R.html">Model Selection</a></li>
<li><a href="Logistic-Regression-With-R.html">Logistic Regression</a></li>
<li><a href="Environments.html">Advanced Linear Regression</a></li>
<li class="dropdown-header">Advanced Regression Models</li>
<li><a href="adv-regression-models.html">Advanced Regression Models</a></li>
<li class="dropdown-header">Time Series</li>
<li><a href="Time-Series-Analysis-With-R.html">Time Series Analysis</a></li>
<li><a href="Time-Series-Forecasting-With-R.html">Time Series Forecasting </a></li>
<li><a href="Time-Series-Forecasting-With-R-part2.html">More Time Series Forecasting</a></li>
<li class="dropdown-header">High Performance Computing</li>
<li><a href="Parallel-Computing-With-R.html">Parallel computing</a></li>
<li><a href="Strategies-To-Improve-And-Speedup-R-Code.html">Strategies to Speedup R code</a></li>
<li class="dropdown-header">Useful Techniques</li>
<li><a href="Association-Mining-With-R.html">Association Mining</a></li>
<li><a href="Multi-Dimensional-Scaling-With-R.html">Multi Dimensional Scaling</a></li>
<li><a href="Profiling.html">Optimization</a></li>
<li><a href="Information-Value-With-R.html">InformationValue package</a></li>
</ul>
</li>
</div>
<div class="well">
<p>Stay up-to-date. <a href="https://docs.google.com/forms/d/1xkMYkLNFU9U39Dd8S_2JC0p8B5t6_Yq6zUQjanQQJpY/viewform">Subscribe!</a></p>
<p><a href="https://docs.google.com/forms/d/13GrkCFcNa-TOIllQghsz2SIEbc-YqY9eJX02B19l5Ow/viewform">Chat!</a></p>
</div>
<h4>Contents</h4>
<ul class="list-unstyled" id="toc"></ul>
<!--
<hr>
<p><a href="/contribute.html">How to contribute</a></p>
<p><a class="btn btn-primary" href="">Edit this page</a></p>
-->
</div>
<div id="content" class="col-xs-12 col-sm-8 pull-right">
<h1>Strategies to Speed-up R Code</h1>
<blockquote>
<p>The for-loop in R, can be very slow in its raw un-optimized form, especially when dealing with larger data sets. There are a number of ways you can make your logics run fast, but you will be really surprised how fast you can actually go. This chapter shows a number of approaches including simple tweaks to logic design, parallel processing and Rcpp, increasing the speed by orders of several magnitudes, so you can comfortably process data as large as 100 Million rows and more.</p>
</blockquote>
<p>Lets try to improve the speed of a logic that involves a for-loop and a condition checking statement (if-else) to create a column that gets appended to the input data frame (df). The code below creates that initial input data frame.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Create the data frame</span>
col1 <-<span class="st"> </span><span class="kw">runif</span> (<span class="dv">12</span>^<span class="dv">5</span>, <span class="dv">0</span>, <span class="dv">2</span>)
col2 <-<span class="st"> </span><span class="kw">rnorm</span> (<span class="dv">12</span>^<span class="dv">5</span>, <span class="dv">0</span>, <span class="dv">2</span>)
col3 <-<span class="st"> </span><span class="kw">rpois</span> (<span class="dv">12</span>^<span class="dv">5</span>, <span class="dv">3</span>)
col4 <-<span class="st"> </span><span class="kw">rchisq</span> (<span class="dv">12</span>^<span class="dv">5</span>, <span class="dv">2</span>)
df <-<span class="st"> </span><span class="kw">data.frame</span> (col1, col2, col3, col4)
df
<span class="co">#> col1 col2 col3 col4</span>
<span class="co">#> 1 0.6155322 -2.91525449 2 6.12523968</span>
<span class="co">#> 2 0.5153450 -5.81655916 6 2.97873584</span>
<span class="co">#> 3 1.1046449 0.80309503 2 0.07266261</span>
<span class="co">#> 4 0.1127663 -1.48824042 3 2.39918101</span>
<span class="co">#> 5 0.9370986 -1.35786823 0 7.38580513</span>
<span class="co">#> 6 0.9675415 0.05832758 2 1.17428455</span></code></pre></div>
<h4>The logic we are about to optimize:</h4>
<p>For every row on this data frame <code>df</code>, check if the sum of all values is greater than 4. If it is, a new 5th variable gets the value <code>greater_than_4</code>, else, it gets <code>lesser_than_4</code>.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># Original R code: Before vectorization and pre-allocation</span>
<span class="kw">system.time</span>({
for (i in <span class="dv">1</span>:<span class="kw">nrow</span>(df)) { <span class="co"># for every row</span>
if ((df[i, <span class="st">'col1'</span>] +<span class="st"> </span>df[i, <span class="st">'col2'</span>] +<span class="st"> </span>df[i, <span class="st">'col3'</span>] +<span class="st"> </span>df[i, <span class="st">'col4'</span>]) ><span class="st"> </span><span class="dv">4</span>) { <span class="co"># check if > 4</span>
df[i, <span class="dv">5</span>] <-<span class="st"> "greater_than_4"</span> <span class="co"># assign 5th column</span>
} else {
df[i, <span class="dv">5</span>] <-<span class="st"> "lesser_than_4"</span> <span class="co"># assign 5th column</span>
}
}
})
<span class="kw">head</span>(df)
<span class="co">#> col1 col2 col3 col4 V5</span>
<span class="co">#> 1 0.6155322 -2.91525449 2 6.12523968 greater_than_4</span>
<span class="co">#> 2 0.5153450 -5.81655916 6 2.97873584 lesser_than_4</span>
<span class="co">#> 3 1.1046449 0.80309503 2 0.07266261 lesser_than_4</span>
<span class="co">#> 4 0.1127663 -1.48824042 3 2.39918101 greater_than_4</span>
<span class="co">#> 5 0.9370986 -1.35786823 0 7.38580513 greater_than_4</span>
<span class="co">#> 6 0.9675415 0.05832758 2 1.17428455 greater_than_4</span></code></pre></div>
<p>All the approaches we see below re-creates the same logic but will do it more efficiently.</p>
<p>All the computations below, for processing times, were done on a MAC OS X with 2.6 Ghz processor and 8GB RAM.</p>
<h2>1. Vectorize and Pre-allocate</h2>
<p>Always initialize your data structures and output variable to required length and data type before taking it to loop for computations. Try not to incrementally increase the size of your data inside the loop. Lets compare how vectorization improves speed on a range of data sizes from 1000 to 100,000 rows.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># After vectorization and pre-allocation</span>
output <-<span class="st"> </span><span class="kw">character</span> (<span class="kw">nrow</span>(df)) <span class="co"># initialize output vector</span>
<span class="kw">system.time</span>({
for (i in <span class="dv">1</span>:<span class="kw">nrow</span>(df)) {
if ((df[i, <span class="st">'col1'</span>] +<span class="st"> </span>df[i, <span class="st">'col2'</span>] +<span class="st"> </span>df[i, <span class="st">'col3'</span>] +<span class="st"> </span>df[i, <span class="st">'col4'</span>]) ><span class="st"> </span><span class="dv">4</span>) {
output[i] <-<span class="st"> "greater_than_4"</span> <span class="co"># assign to vector </span>
} else {
output[i] <-<span class="st"> "lesser_than_4"</span>
}
}
df$output <-<span class="st"> </span>output <span class="co"># finally assign to data frame</span>
})</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-1.png' width='447' height='300' /></p>
<h2>2. Take statements that check for conditions (if statements) outside the loop</h2>
<p>Taking the condition checking outside the loop the speed is compared against the previous version that had vectorization alone. The tests were done on dataset size range from 100,000 to 1,000,000 rows. The gain in speed is again dramatic.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># After vectorization and pre-allocation, taking the condition checking outside the loop.</span>
output <-<span class="st"> </span><span class="kw">character</span> (<span class="kw">nrow</span>(df))
condition <-<span class="st"> </span>(df$col1 +<span class="st"> </span>df$col2 +<span class="st"> </span>df$col3 +<span class="st"> </span>df$col4) ><span class="st"> </span><span class="dv">4</span> <span class="co"># condition check outside the loop</span>
<span class="kw">system.time</span>({
for (i in <span class="dv">1</span>:<span class="kw">nrow</span>(df)) {
if (condition[i]) {
output[i] <-<span class="st"> "greater_than_4"</span>
} else {
output[i] <-<span class="st"> "lesser_than_4"</span>
}
}
df$output <-<span class="st"> </span>output
})</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-2.png' width='447' height='299' /></p>
<h2>3. Run the loop only for True conditions</h2>
<p>Another optimization we can do here is to run the loop only for condition cases that are ‘True’, by initializing (pre-allocating) the default value of output vector to that of ‘False’ state. The speed improvement here largely depends on the proportion of ‘True’ cases in your data. The tests compared the performance of this against the previous case (2) on data size ranging from 1,000,000 to 10,000,000 rows. Note that we have increase a ‘0’ here. As expected there is a consistent and considerable improvement.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">output <-<span class="st"> </span><span class="kw">character</span>(<span class="kw">nrow</span>(df))
condition <-<span class="st"> </span>(df$col1 +<span class="st"> </span>df$col2 +<span class="st"> </span>df$col3 +<span class="st"> </span>df$col4) ><span class="st"> </span><span class="dv">4</span>
<span class="kw">system.time</span>({
for (i in (<span class="dv">1</span>:<span class="kw">nrow</span>(df))[condition]) { <span class="co"># run loop only for true conditions</span>
if (condition[i]) {
output[i] <-<span class="st"> "greater_than_4"</span>
} else {
output[i] <-<span class="st"> "lesser_than_4"</span>
}
}
df$output })</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-3.png' width='447' height='302' /></p>
<h2>4. Use ifelse() whenever possible</h2>
<p>You can make this logic much simpler and faster by using the ifelse() statement. The syntax is similar to the ‘if’ function in MS Excel, but the speed increase is phenomenal, especially considering that there is no vector pre-allocation here and the condition is checked in every case. Looks like this is going to be a highly preferred option to speed up simple loops.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">system.time</span>({
output <-<span class="st"> </span><span class="kw">ifelse</span> ((df$col1 +<span class="st"> </span>df$col2 +<span class="st"> </span>df$col3 +<span class="st"> </span>df$col4) ><span class="st"> </span><span class="dv">4</span>, <span class="st">"greater_than_4"</span>, <span class="st">"lesser_than_4"</span>)
df$output <-<span class="st"> </span>output
})</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-4.png' width='447' height='335' /></p>
<h2>5. Using which()</h2>
<p>By using which() command to select the rows, we are able to achieve one-third the speed of Rcpp.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">system.time</span>({
want =<span class="st"> </span><span class="kw">which</span>(<span class="kw">rowSums</span>(df) ><span class="st"> </span><span class="dv">4</span>)
output =<span class="st"> </span><span class="kw">rep</span>(<span class="st">"less than 4"</span>, <span class="dt">times =</span> <span class="kw">nrow</span>(df))
output[want] =<span class="st"> "greater than 4"</span>
})
<span class="co"># nrow = 3 Million rows (approx)</span>
<span class="co">#> user system elapsed </span>
<span class="co">#> 0.396 0.074 0.481 </span></code></pre></div>
<h2>6. Use apply family of functions instead of for-loops.</h2>
<p>Using apply() function to compute the same logic and comparing it against the vectorized for-loop. The results again is faster in order of magnitudes but slower than <code>ifelse()</code> and the version where condition checking was done outside the loop. This can be very useful, but you will need to be a bit crafty when handling complex logic.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># apply family</span>
<span class="kw">system.time</span>({
myfunc <-<span class="st"> </span>function(x) {
if ((x[<span class="st">'col1'</span>] +<span class="st"> </span>x[<span class="st">'col2'</span>] +<span class="st"> </span>x[<span class="st">'col3'</span>] +<span class="st"> </span>x[<span class="st">'col4'</span>]) ><span class="st"> </span><span class="dv">4</span>) {
<span class="st">"greater_than_4"</span>
} else {
<span class="st">"lesser_than_4"</span>
}
}
output <-<span class="st"> </span><span class="kw">apply</span>(df[, <span class="kw">c</span>(<span class="dv">1</span>:<span class="dv">4</span>)], <span class="dv">1</span>, <span class="dt">FUN=</span>myfunc) <span class="co"># apply 'myfunc' on every row</span>
df$output <-<span class="st"> </span>output
})</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-5.png' width='447' height='325' /></p>
<h2>7. Use byte code compilation for functions <code>cmpfun()</code> from compiler package, rather than the actual function itself.</h2>
<p>This may not be the best example to illustrate the effectiveness of byte code compilation, as the time taken is marginally higher than the regular form. However, for more complex functions, byte-code compilation is known to perform faster. So you should definitely give it a shot.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># byte code compilation</span>
<span class="kw">library</span>(compiler)
myFuncCmp <-<span class="st"> </span><span class="kw">cmpfun</span>(myfunc)
<span class="kw">system.time</span>({
output <-<span class="st"> </span><span class="kw">apply</span>(df[, <span class="kw">c</span> (<span class="dv">1</span>:<span class="dv">4</span>)], <span class="dv">1</span>, <span class="dt">FUN=</span>myFuncCmp)
})</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-6.png' width='447' height='359' /></p>
<h2>8. Use Rcpp</h2>
<p>Lets turn this up a notch. So far we have gained speed and capacity by various strategies and found the most optimal one using the ifelse() statement. What if we add one more zero? Below we execute the same logic but with Rcpp, and with a data size is increased to 100 Million rows. We will compare the speed of Rcpp to the ifelse() method.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="kw">library</span>(Rcpp)
<span class="kw">sourceCpp</span>(<span class="st">"MyFunc.cpp"</span>)
<span class="kw">system.time</span> (output <-<span class="st"> </span><span class="kw">myFunc</span>(df)) <span class="co"># see Rcpp function below</span></code></pre></div>
<p>Below is the same logic executed in C++ code using Rcpp package. Save the code below as “MyFunc.cpp” in your R session’s working directory (else you just have to sourceCpp from the full file path). Note: the <code>// [[Rcpp::export]]</code> comment is mandatory and has to be placed just before the function that you want to execute from R.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">/<span class="er">/</span><span class="st"> </span>Source for MyFunc.cpp
<span class="co">#include <Rcpp.h></span>
using namespace Rcpp;
/<span class="er">/</span><span class="st"> </span>[[Rcpp::export]]
CharacterVector <span class="kw">myFunc</span>(DataFrame x) {
NumericVector col1 =<span class="st"> </span>as<NumericVector>(x[<span class="st">"col1"</span>]);
NumericVector col2 =<span class="st"> </span>as<NumericVector>(x[<span class="st">"col2"</span>]);
NumericVector col3 =<span class="st"> </span>as<NumericVector>(x[<span class="st">"col3"</span>]);
NumericVector col4 =<span class="st"> </span>as<NumericVector>(x[<span class="st">"col4"</span>]);
int n =<span class="st"> </span><span class="kw">col1.size</span>();
CharacterVector <span class="kw">out</span>(n);
for (int <span class="dt">i=</span><span class="dv">0</span>; i<n; i++) {
double tempOut =<span class="st"> </span>col1[i] +<span class="st"> </span>col2[i] +<span class="st"> </span>col3[i] +<span class="st"> </span>col4[i];
if (tempOut ><span class="st"> </span><span class="dv">4</span>){
out[i] =<span class="st"> "greater_than_4"</span>;
} else {
out[i] =<span class="st"> "lesser_than_4"</span>;
}
}
return out;
}</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-7.png' width='447' height='360' /></p>
<h2>9. Use parallel processing if you have a multicore machine.</h2>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r"><span class="co"># parallel processing</span>
<span class="kw">library</span>(foreach)
<span class="kw">library</span>(doSNOW)
cl <-<span class="st"> </span><span class="kw">makeCluster</span>(<span class="dv">4</span>, <span class="dt">type=</span><span class="st">"SOCK"</span>) <span class="co"># for 4 cores machine</span>
<span class="kw">registerDoSNOW</span> (cl)
condition <-<span class="st"> </span>(df$col1 +<span class="st"> </span>df$col2 +<span class="st"> </span>df$col3 +<span class="st"> </span>df$col4) ><span class="st"> </span><span class="dv">4</span>
<span class="co"># parallelization with vectorization</span>
<span class="kw">system.time</span>({
output <-<span class="st"> </span><span class="kw">foreach</span>(<span class="dt">i =</span> <span class="dv">1</span>:<span class="kw">nrow</span>(df), <span class="dt">.combine=</span>c) %dopar%<span class="st"> </span>{
if (condition[i]) {
<span class="kw">return</span>(<span class="st">"greater_than_4"</span>)
} else {
<span class="kw">return</span>(<span class="st">"lesser_than_4"</span>)
}
}
})
df$output <-<span class="st"> </span>output</code></pre></div>
<h2>10. Remove variables and flush memory as early as possible.</h2>
<p>Remove objects <code>rm()</code> that are no longer needed, as early as possible in code, especially before going in to lengthy loop operations. Sometimes, flushing <code>gc()</code> at the end of each iteration with in the loops can help.</p>
<h2>11. Use data structures that consume less memory</h2>
<p><code>data.table()</code> is an excellent example, as it reduces the memory overload which helps to speed up operations like merging data.</p>
<div class="sourceCode"><pre class="sourceCode r"><code class="sourceCode r">dt <-<span class="st"> </span><span class="kw">data.table</span>(df) <span class="co"># create the data.table</span>
<span class="kw">system.time</span>({
for (i in <span class="dv">1</span>:<span class="kw">nrow</span> (dt)) {
if ((dt[i, col1] +<span class="st"> </span>dt[i, col2] +<span class="st"> </span>dt[i, col3] +<span class="st"> </span>dt[i, col4]) ><span class="st"> </span><span class="dv">4</span>) {
dt[i, col5:<span class="er">=</span><span class="st">"greater_than_4"</span>] <span class="co"># assign the output as 5th column</span>
} else {
dt[i, col5:<span class="er">=</span><span class="st">"lesser_than_4"</span>] <span class="co"># assign the output as 5th column</span>
}
}
})</code></pre></div>
<p><img src='screenshots/strategies-to-speedup-r-code/strategies-to-speedup-r-code-8.png' width='447' height='360' /></p>
<h2>Summary</h2>
<table>
<thead>
<tr class="header">
<th align="left">Method</th>
<th align="left">Speed</th>
<th align="left">nrow(df)/time_taken = <em>n</em> rows per second</th>
</tr>
</thead>
<tbody>
<tr class="odd">
<td align="left">Raw</td>
<td align="left">1X</td>
<td align="left">120000/140.15 = 856.2255 rows per second (normalized to 1)</td>
</tr>
<tr class="even">
<td align="left">Vectorized</td>
<td align="left">738X</td>
<td align="left">120000/0.19 = 631578.9 rows per second</td>
</tr>
<tr class="odd">
<td align="left">True Conditions only</td>
<td align="left">1002X</td>
<td align="left">120000/0.14 = 857142.9 rows per second</td>
</tr>
<tr class="even">
<td align="left">ifelse</td>
<td align="left">1752X</td>
<td align="left">1200000/0.78 = 1500000 rows per second</td>
</tr>
<tr class="odd">
<td align="left">which</td>
<td align="left">8806X</td>
<td align="left">2985984/0.396 = 7540364 rows per second</td>
</tr>
<tr class="even">
<td align="left">Rcpp</td>
<td align="left">13476X</td>
<td align="left">1200000/0.09 = 11538462 rows per second</td>
</tr>
</tbody>
</table>
<p>The numbers above are approximate and are based in arbitrary runs. The results are not calculated for data.table(), byte code compilation and parallelisation methods as they will vary on a case to case basis, depending upon how you apply it.</p>
</div>
</div>
<div class="footer">
<hr>
<p>© 2016-17 Selva Prabhakaran. Powered by <a href="http://jekyllrb.com/">jekyll</a>,
<a href="http://yihui.name/knitr/">knitr</a>, and
<a href="http://johnmacfarlane.net/pandoc/">pandoc</a>.
This work is licensed under the <a href="http://creativecommons.org/licenses/by-nc/3.0/">Creative Commons License.</a>
</p>
</div>
</div> <!-- /container -->
<script src="//code.jquery.com/jquery.js"></script>
<script src="www/bootstrap.min.js"></script>
<script src="www/toc.js"></script>
<!-- MathJax Script -->
<script type="text/x-mathjax-config">
MathJax.Hub.Config({
tex2jax: {inlineMath: [['$','$'], ['\\(','\\)']]}
});
</script>
<script type="text/javascript"
src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML">
</script>
<!-- Google Analytics Code -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-69351797-1', 'auto');
ga('send', 'pageview');
</script>
<style type="text/css">
/* reduce spacing around math formula*/
.MathJax_Display {
margin: 0em 0em;
}
body {
font-family: 'Helvetica Neue', Roboto, Arial, sans-serif;
font-size: 16px;
line-height: 27px;
font-weight: 400;
}
blockquote p {
line-height: 1.75;
color: #717171;
}
.well li{
line-height: 28px;
}
li.dropdown-header {
display: block;
padding: 0px;
font-size: 14px;
}
</style>
</body>
</html>