如果我 运行 来自 R 控制台的程序作为脚本,parLapply 真的很慢,但如果我 运行 我的代码在 rstudio 中逐行

parLapply is realy slow if i run the program from an R console as a script but realy fast if i run my code line by line in rstudio

如果我 运行 我的代码是交互式的,即在 Rstudio 中逐行运行,一切正常,而且速度非常快。 一旦我尝试 运行 我的代码作为脚本,parLapply 就会花费很长时间。 好像在等待什么,或者被什么东西挡住了。 Top 还显示 R 进程产生并暂时处于非活动状态。

在这两种情况下,代码将产生相同的结果。 我很难提供可以证明问题的代码示例 因为只要我不使用大型结构,这个问题就不会产生。

我写了一个小例子来演示这个问题,但是因为我不使用大的嵌套列表或者 xml 这个问题就不会发生。 我知道这远非理想的问题,但也许有人有过提示或遇到过同样的问题。

library(parallel)
library(osmar)

src <- osmsource_api(url = "https://api.openstreetmap.org/api/0.6/")
muc_bbox <- center_bbox(11.575278, 48.137222, 10000, 10000)
test_osm <- get_osm(muc_bbox, src)

n.cores <- detectCores()

wegpunkte<-list(c(id = 7018492265, lon = 11.8303853, lat = 48.1102703), 
                c(id = 94064123, lon = 12.1768446, lat = 48.1265051), 
                c(id = 1532819835,lon = 12.0014881, lat = 47.8225144), 
                c(id = 130221481, lon = 12.2078502, lat = 47.8395169))

find_a_node <- function(osm_object,search_lon,search_lat){
  nodes_ids_found <- osmar::find(osm_object, node(attrs(lon>search_lon & lat > search_lat )))
  if(anyNA((nodes_ids_found)))
  {
    nodes_ids_found <- osmar::find(osm_object, node(attrs(lon < search_lon & lat < search_lat )))
  }
  nodes_found <- base::subset(osm_object,nodes_ids_found)
  node_coords <- data.frame(nodes_found$nodes$attrs[, c("id","lon", "lat")])
  node_coords$dist <- geodist_vec(x1 = node_coords$lon,y1 = node_coords$lat,x2 = search_lon,y2 = search_lat,measure = "haversine")
  point_result <- node_coords[which.min(node_coords$dist),]
  nodes_found <- base::subset(nodes_found,point_result$id)
  print(point_result)
  return(base::subset(nodes_found,nodes_found$nodes$attrs$id))
}

tictoc::tic()
clust <- makeCluster(n.cores,type="FORK",outfile="test")
wegpunkte_nodes <- parLapply(clust,wegpunkte, function(x) find_a_node(test_osm,x[[1]],x[[2]]))
stopCluster(clust)
tictoc::toc()

我用mcmapply解决了这个问题