我正在处理另一个类项目,我必须测量system.time
迭代循环以将函数与cbind
进行比较。
我的大部分内容都有效,但是现在,system.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
这就是它打印出来的内容(为了整洁的演示而被截断):
size fast slow
1 200 NA NA
2 400 NA NA
3 600 NA NA
4 800 NA NA
5 1000 NA NA
. . . .
. . . .
. . . .
有什么想法吗?
答案 0 :(得分:3)
更改
as.vector(times[n])
到
as.vector(times[3])
然后一切正常。 system.time()
返回长度为5的向量,其第3个元素是挂钟时间。但是,您要求n
元素,而n
始终大于5。
尝试以下操作,然后您将了解system.time()
返回的内容:
x = system.time(runif(1000000, 0, 1)
x[1:10]
<强>更新强>
你知道,实际上,你的代码远非一切正常。即使在对system.time()
进行更正后,您的循环仍然看起来很可疑(请参阅我的评论):
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
很遗憾,您的版本myCbind
并不比cbind
好!