Could anybody help me to somehow parallelize this code ? I am about to make some simulations but I STACKED... it takes too long - I even left my computer for 3 days and it did not finished calculating
sapply(1:1000, Take_expected_value, points =10^7, number_of_trajectories = 10^7) Take_expected_value <- function(interval_end = 1, points = 100, number_of_trajectories = 1000){ return( mean( exp( replicate( n = number_of_trajectories, expr = Max_from_Wiener_on_interval(interval_end, points) ) ) ) ) # This function just replicates max_from_... function, then put values # to exp function, and calculates mean of all replications. } Max_from_Wiener_on_interval <- function(interval_end = 1, points = 100){ # time increment Delta <- interval_end/points # time moments time <- seq( 0, interval_end, length = points + 1) # Wiener process W <- cumsum( sqrt(Delta) * rnorm( points + 1 ) ) # return max of "Wiener * sqrt(2) - time moment" return( max(sqrt(2) * W - time) ) } EDIT
After EDIT I am using this code, but it might be a problem of my weak machine(computer). Still it is very slow for me:
Take_expected_value <- function(interval_end = 1, points = 100, number_of_trajectories = 1000){ return( mean( exp( replicate( n = number_of_trajectories, expr = Max_from_Wiener_on_interval(interval_end, points) ) ) ) ) # This function just replicates max_from_... function, then put values # to exp function, and calculates mean of all replications. } # this function shall not be exported Max_from_Wiener_on_interval <- function(interval_end = 1, points = 100){ # time increment Delta <- interval_end/points # time moments time <- seq( 0, interval_end, length = points + 1) # Wiener process W <- cumsum( sqrt(Delta) * rnorm( points + 1 ) ) # return max of "Wiener * sqrt(2) - time moment" return( max(sqrt(2) * W - time) ) } install.packages("snowfall") require(snowfall) cpucores=as.integer(Sys.getenv('NUMBER_OF_PROCESSORS')) sfInit( parallel=T, cpus=cpucores) # sfExportAll() system.time( sfLapply(as.list(c(1:1000)),fun=Take_expected_value, points =10^6, number_of_trajectories = 10^6) ) sfRemoveAll() sfStop()
sapplyis just a giant loop, and loops runs like molasses in R. Pretty trivial to convert this code toJulia, and should be substantially faster.