Commit 8520de7 Hua Zhou
committed
1 parent 411b52b commit 8520de7 Copy full SHA for 8520de7
File tree 2 files changed +163
-0
lines changed
2 files changed +163
-0
lines changed Original file line number Diff line number Diff line change
1
+ ---
2
+ title : " JIT"
3
+ author : " Hua Zhou"
4
+ date : " September 9, 2014"
5
+ output : html_document
6
+ ---
7
+
8
+ This example explores the JIT (just-in-time) compilation in R using the ` compiler ` package.
9
+
10
+ Brute-force ` for ` loop for summing a vector
11
+ ``` {r}
12
+ testfor <- function(x) {
13
+ sumx <- 0.0
14
+ for (i in 1:length(x)) {
15
+ sumx <- sumx + x[i]
16
+ }
17
+ return(sumx)
18
+ }
19
+ ```
20
+ Vectorized form
21
+ ``` {r}
22
+ testvec <- function(x) {
23
+ return(sum(x))
24
+ }
25
+ ```
26
+
27
+ Run the code on 1e6 elements
28
+ ``` {r}
29
+ x = seq(from = 0, to = 100, by = 0.0001)
30
+ system.time(testfor(x))
31
+ system.time(testvec(x))
32
+ ```
33
+
34
+ Let's load the ` compiler ` package and compile the ` testfor ` function
35
+ ``` {r}
36
+ library(compiler)
37
+ ctestfor <- cmpfun(testfor)
38
+ ```
39
+ Re-run the functions
40
+ ``` {r}
41
+ system.time(testfor(x))
42
+ system.time(ctestfor(x))
43
+ system.time(testvec(x))
44
+ ```
Load Diff Large diffs are not rendered by default.
You can’t perform that action at this time.
0 commit comments