Skip to content

Instantly share code, notes, and snippets.

@emhart
Created September 11, 2012 18:05
Show Gist options
  • Save emhart/3700368 to your computer and use it in GitHub Desktop.
Save emhart/3700368 to your computer and use it in GitHub Desktop.
How to exit a function after a certain time period in R
# The data in the list you want to use lapply with
my_dat <- as.list(sample(1:10000,10, replace=T))
foo_time <- function(dat,time_thresh = 2){
start_time <- proc.time()
end_time <- 0
for(i in 1:dat){
###Put the actual function you want to call within this for loop
X <- matrix(rnorm(1000),1000)
tmp <- X%*%t(X)
##### After a single iteration of your process calculate the time
end_time <- proc.time() - start_time
### check the time. If it's too long break out of the loop and return a value
if(end_time[1] >= time_thresh){
break()
}
}
return(end_time[1])
}
### Note that all times are shorter than the time threshold
lapply(my_dat,foo_time,time_thresh = 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment