r - 如果因子不是 1,向量乘法更快
问题描述
我目前面临一个我没有任何解释的问题。基本上在一个循环中,我将 100 个随机点的向量与一个数字相乘。像这样:
for(i in 1:10000) {
xs <- runif(100,0,1)
ys <- runif(100,0,1)
data <- factor*cbind(xs,ys)
#do something with the data
}
例如,如果我设置factor <- 3
它工作正常,一段时间后我就有了我的结果。但是如果因子设置为 1(作为函数的参数),它需要永远。这种行为有什么合乎逻辑的原因吗?非常感谢!
解决方案
正如@ThomasIscoding 所说,这一定是关于你接下来要做什么的事情,因为用,或for loop
调用那段代码没有显着区别:factor = 1
factor = 1 / 2 * 2
factor = 3
library(microbenchmark)
fn <- function(factor = 1) {
for (i in 1:10000) {
xs <- runif(100, 0, 1)
ys <- runif(100, 0, 1)
data <- factor * cbind(xs, ys)
#do something with the data
}
return(data)
}
microbenchmark(fn(1),
fn(1 / 2 * 2),
fn(3),
times = 10L)
#> Unit: milliseconds
#> expr min lq mean median uq max neval cld
#> fn(1) 102.8349 108.2655 109.9209 108.6099 111.8287 122.4011 10 a
#> fn(1/2 * 2) 101.8430 103.7025 112.1260 107.5010 111.9726 150.9856 10 a
#> fn(3) 102.3946 105.0698 109.6703 107.7922 114.4457 119.2038 10 a
由reprex 包(v0.3.0)于 2020-04-16 创建
推荐阅读
- jquery - 如何检查第三方 jquery 文件是否完全加载
- ember.js - Ember.js:并行加载父子模型
- flutter - TextEditingController 不会在 Web 上更改 TextEdit 的文本。可能是 EditText 的其他解决方案吗?
- ubuntu - 在具有非 gui 模式的 ubuntu jmeter 上运行脚本时出错
- html - Chrome/Safari中空的意外定位
- javascript - 检查 webview 的 shouldInterceptRequest 是否会被调用?
- javascript - 如何从 React 本机应用程序在设备浏览器中打开 POST url
- php - 作曲家要求后找不到类
- php - 尝试在 PHP 中上传文件时,如何防止页面重新加载并且什么都不做?
- c# - 除了 iText 之外,是否有任何使用 c# 的开源 PDF 表单填充器