-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path607_performanceQuiz_satz.R
More file actions
75 lines (56 loc) · 1.39 KB
/
607_performanceQuiz_satz.R
File metadata and controls
75 lines (56 loc) · 1.39 KB
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
## Alex Satz
## Nov 29 2014
## IS607 performance Quiz
## Part I.
library(Rcpp)
library(microbenchmark)
## the function below was taken from Hadley's book as a test
cppFunction('int add(int x, int y, int z) {
int sum = x + y + z;
return sum;
}')
add(1, 2, 3)
## and this function I wrote. It replaces the number 10 with the number 9.
## Granted, not that usefull...I wanted to use the '%' to get a remainder, but
## I cannot get this to work with cppFunction?
cppFunction('NumericVector allodd(NumericVector x)
{
int n = x.size();
for(int i = 0; i < n; ++i) {
if (x[i] == 10){
x[i]= 9;
}
}
return x;
}')
## This does the same thing in 'R'
rallodd <-function(vec){
for (i in 1:length(vec)){
if (vec[i] == 10){
vec[i] = 9
}
}
return (vec)
}
## This function creates a new vector instead assigning values inplace.
rallodd2 <-function(vec){
temp <-0
for (i in 1:length(vec)){
if (vec[i] == 10){
temp[i] = 9
}
else{
temp[i] = vec[i]
}
}
return (temp)
}
v <- runif(10, 8,12)
v <- as.integer(v)
x <-allodd(v)
microbenchmark(newv <-allodd(v))
microbenchmark(newv <-rallodd(v))
microbenchmark(newv <-rallodd2(v))
## C++ takes 6.7 microseconds, R with single vector takes 20 usec,
## R generating new vector takes 39 usec.
##########################################################################################