-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path05-sugar.Rmd
93 lines (74 loc) · 2.56 KB
/
05-sugar.Rmd
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
```{R echo = FALSE, warnings = FALSE}
source("include.cpp.r")
includeCppPath <- "../introRcppSugar/src//"
```
# Sucre syntaxique
All the examples are in the R package...
Install it with
```{R eval = FALSE, prompt = TRUE}
devtools::install_github("introRcpp/introRcppSugar")
```
Load it with
```{R}
library(introRcppSugar)
```
La fonction R suivante fait un usage abondant de la vectorisation.
```{r prompt = FALSE}
bonne.vectorisation <- function(x, y) {
z <- 3*x + y
if(any(x > 1))
z <- z*2;
sum( ifelse(z > 0, z, y) )
}
```
```{r prompt = TRUE, comment = NA}
set.seed(1); x <- rnorm(10); y <- rnorm(10)
bonne.vectorisation(x,y)
```
La transcription en C++ devrait faire intevenir trois boucles ;
c'est un peu fastidieux. Le sucre syntaxique ajouté par les fonctions
dites *Rcpp sugar* permet d'éviter de les écrire.
```{R echo = FALSE, results = "asis"}
include.cpp('fonction_sucree.cpp')
```
```{r prompt = TRUE, comment = NA}
fonction_sucree(x,y)
```
## Efficacité
Grâce à une implémentation soignée, les fonctions Rcpp sugar sont redoutablement efficaces.
```{r prompt = TRUE, comment = NA, fig.width = 5, fig.height = 2, fig.align = 'center', message = FALSE, cache = TRUE}
x <- rnorm(1e6)
y <- rnorm(1e6)
mbm <- microbenchmark::microbenchmark( bonne.vectorisation(x,y), fonction_sucree(x,y) )
mbm
ggplot2::autoplot(mbm)
```
Revenons cependant à notre exemple de comptage de 0 dans un vecteur.
```{R echo = FALSE, results = "asis"}
include.cpp('countZeroesSugar.cpp')
```
Comparons cette solution à celle proposée au chapitre précédent.
```{r prompt = TRUE, comment = NA, fig.width = 5, fig.height = 2, fig.align = 'center', message = FALSE, cache = TRUE}
set.seed(1); a <- sample(0:99, 1e6, TRUE)
sum(a == 0);
countZeroesSugar(a);
countZeroes(a);
mbm <- microbenchmark::microbenchmark( R = sum(a == 0), Cpp_sugar = countZeroesSugar(a), Cpp = countZeroes(a))
mbm
ggplot2::autoplot(mbm)
```
On le voit, la fonction qui utilise le sucre syntaxique, bien que toujours
très efficace, n'atteint pas toujours la performance d'une fonction plus rustique.
## Un exemple de la Rcpp Gallery
Un exemple tiré de la Rcpp Gallery http://gallery.rcpp.org/articles/simulating-pi/
(estimation de $\pi$ par la méthode de Monte-Carlo) et la variante avec une boucle.
```{R echo = FALSE, results = "asis"}
include.cpp('pi_sugar.cpp')
```
```{r prompt = TRUE, comment = NA, fig.width = 5, fig.height = 2, fig.align = 'center', message = FALSE, cache = TRUE}
pi_sugar(1e6)
pi_boucle(1e6)
mbm <- microbenchmark::microbenchmark(pi_sugar(1e6), pi_boucle(1e6))
mbm
ggplot2::autoplot(mbm)
```