Repository navigation
Expand file tree
/
Copy pathBenchReturn.qmd
More file actions
124 lines (115 loc) · 1.91 KB
/
Copy pathBenchReturn.qmd
File metadata and controls
124 lines (115 loc) · 1.91 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
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
---
title: "BenchReturn"
author: "ThomasReinke"
format: html
editor_options:
chunk_output_type: console
---
```{r setup}
#| echo: false
#| include: false
knitr::opts_chunk$set(
collapse = TRUE, comment = "#"
)
knitr::opts_chunk$set(tidy.opts = list(width.cutoff = 60), tidy = TRUE)
#source(here::here("helpers.R"))
library("tidyverse"); library("patchwork"); library("glue")
library("scales", warn.conflicts = FALSE); library("extrafont")
theme_set(theme_minimal())
theme_update(panel.grid.minor = element_blank())
```
## To return or not to return
### A function that simply returns true
```{r}
no_return <- function(n){
TRUE
}
```
```{r}
yes_return <- function(n){
return(TRUE)
}
```
```{r}
#| cache: true
# benchmark and plot results
res <- bench::press(
n = c(1, 2),
{
bench::mark(
yes_return(n),
no_return(n)
)
}
)
res
plot(res)
```
### A function that copies and returns a matrix
```{r}
matrix_return <- function(A){
B <- A
return(B)
}
```
```{r}
matrix_no_return <- function(A){
B <- A
B
}
```
```{r}
#| cache: true
# benchmark and plot results
res <- bench::press(
m = c(10, 20, 50, 100),
{
A <- matrix(rnorm(m^2), m) |> crossprod()
bench::mark(
matrix_no_return(A),
matrix_return(A)
)
}
)
res
plot(res)
```
### Loops
```{r}
loop_return <- function(n){
for(i in seq_along(1:n)){
for(j in seq_along(1:n)){
for(k in seq_along(1:n)){
l <- i * j * k
}
}
}
return(l)
}
```
```{r}
loop_no_return <- function(n){
for(i in seq_along(1:n)){
for(j in seq_along(1:n)){
for(k in seq_along(1:n)){
l <- i * j * k
}
}
}
l
}
```
```{r}
#| cache: true
res <- bench::press(
n = c(1, 10),
{
bench::mark(
matrix_no_return(n),
matrix_return(n)
)
}
)
res
plot(res)
```