R 为什么system.time只返回NA?

R 为什么system.time只返回NA?,r,R,我正在做另一个类项目,我必须测量循环迭代的system.time,以将函数与cbind进行比较 我的大部分工作正常,但现在,系统.time部分只返回NA # Set memory size so it'll stop yelling at me memory.size(max=FALSE) # Set matrixes A <- matrix(runif(n * n), n, n) B <- matrix(runif(n * n), n, n) # Set df df <-

我正在做另一个类项目,我必须测量循环迭代的
system.time
,以将函数与
cbind
进行比较

我的大部分工作正常,但现在,
系统.time
部分只返回
NA

# Set memory size so it'll stop yelling at me
memory.size(max=FALSE)

# Set matrixes
A <- matrix(runif(n * n), n, n)
B <- matrix(runif(n * n), n, n)

# Set df
df <- data.frame(size=numeric(0),fast=numeric(0),slow=numeric(0))

# Set n
n <- c(200,400,600,800,1000,1200,1400,1600,1800,2000)

# Make a silly cbind-esque function
myCbind <- function(x,y) {
  flatA <- array(x)
  flatB <- array(y)
  comboAB <- data.frame(flatA,flatB)
  return(comboAB)
}

# Loop
for (i in n) {
  cbind(A,B)
  times <- system.time(cbind(A,B))
  fast_time = as.vector(times[n])
  myCbind(A,B)
  times <- system.time(myCbind(A,B))
  slow_time = as.vector(times[n])
  df <- rbind(df, data.frame(size=n, fast=fast_time, slow=slow_time))
}

# Print df to make sure it's working
df
有什么想法吗?

改变

as.vector(times[n])

然后一切都开始了
system.time()
返回长度为5的向量,其中第三个元素是挂钟时间。但是,您要求
n
th元素,而
n
始终大于5

尝试以下操作,然后您将了解
system.time()
返回的内容:

x = system.time(runif(1000000, 0, 1)
x[1:10]

更新:

你知道,实际上,你的代码还远远不够好。即使在对
system.time()
进行了更正之后,您的循环看起来仍然非常可疑(请参阅我的注释):

for(n中的i){
##A,B在哪里???
cbind(A,B)##为什么要打印出来???

你的
n
大于5的可能性有多少次?我没想到它会更快。我希望它会更慢。作业是比较两者,真的。
as.vector(times[3])
x = system.time(runif(1000000, 0, 1)
x[1:10]
for (i in n) {
  ## ? where is A, B ???
  cbind(A,B)  ## why print this out ???
  times <- system.time(cbind(A,B));
  fast_time = as.vector(times[3])
  myCbind(A,B)  ## why print this out ???
  times <- system.time(myCbind(A,B))
  slow_time = as.vector(times[3])
  ## size = n, or size = i ???
  df <- rbind(df, data.frame(size = n, fast = fast_time, slow = slow_time))
  }
n <- c(200,400,600,800,1000,1200,1400,1600,1800,2000)
df <- data.frame(size=numeric(0),fast=numeric(0),slow=numeric(0))

myCbind <- function(x,y) {
  flatA <- array(x)
  flatB <- array(y)
  comboAB <- data.frame(flatA,flatB)
  return(comboAB)
  }

for (i in n) {
  A <- matrix(runif(i * i), i, i)
  B <- matrix(runif(i * i), i, i)
  fast_time <- as.vector(system.time(cbind(A,B)))[3]
  slow_time <- as.vector(system.time(myCbind(A,B)))[3]
  df <- rbind(df, data.frame(size = i, fast = fast_time, slow = slow_time))
  }

> df
   size  fast  slow
1   200 0.000 0.001
2   400 0.003 0.003
3   600 0.007 0.007
4   800 0.013 0.013
5  1000 0.022 0.023
6  1200 0.032 0.032
7  1400 0.044 0.045
8  1600 0.059 0.060
9  1800 0.076 0.077
10 2000 0.094 0.094