Reputation:
I'm working on another class project where I have to measure system.time
for iterations of a loop to compare a function to cbind
.
I have most of it working, but right now, the system.time
part is only returning 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
And this is what it prints out (truncated for neat demonstration):
size fast slow
1 200 NA NA
2 400 NA NA
3 600 NA NA
4 800 NA NA
5 1000 NA NA
. . . .
. . . .
. . . .
Any ideas?
Upvotes: 2
Views: 161
Reputation: 73315
Change
as.vector(times[n])
to
as.vector(times[3])
then everything works. system.time()
returns a vector of length 5, the 3rd element of which is wall clock time. However, you asked for n
th element while n
is always greater than 5.
Try the following, then you will learn what system.time()
returns:
x = system.time(runif(1000000, 0, 1)
x[1:10]
Update:
You know, actually, your code is far from being OK. Even after the correction for system.time()
, your loop still looks really suspicious (see my comments):
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))
}
So, putting it all together, this should be the right one:
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
Unfortunately, your version myCbind
is no better than cbind
!
Upvotes: 2