这是出于好奇而提出的一般性问题。我正在使用该doParallel包进行并行计算。我使用这些包来进行模拟。
我观察到,当我使用foreach循环进行模拟时,Rstudio 中的当前使用内存急剧上升 (4+GiB),并且 Rstudio 有时崩溃。
现在我再次parallel::mclapply进行了相同的模拟,但令人惊讶的是没有问题,并且当前使用内存没有增加太多(10+MiB)。
我不明白代码内部发生了什么。我期待对上述过程的详细解释。
sessionInfo()因为我的 R 是
R version 4.2.1 (2022-06-23) -- "Funny-Looking Kid"
Copyright (C) 2022 The R Foundation for Statistical Computing
Platform: aarch64-apple-darwin20 (64-bit)
Run Code Online (Sandbox Code Playgroud)
操作系统是MacOS。
doParallel软件包版本 1.0.17。
RStudio 版本 2023.03.01。
假设我们正在尝试计算 Erdos-Renyi 图的边数。我试图每次模拟图形并存储每次模拟的边计数值。
代码如下
#ER random graph generator
src1 <- {"#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericMatrix ER_AdjMatGEN_cpp(int N, double p){
NumericMatrix temp(N,N);
for(int i=0; i< N; i++){
for(int j=0; j < i; j++){ …Run Code Online (Sandbox Code Playgroud) 我编写了以下代码来从向量中删除零。我使用erase(i)Rcpp 库中的函数。
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
NumericVector erase_zero(NumericVector x) {
for (int i = 0; i < x.size(); i++) {
if (x[i] == 0) {
x.erase(i);
}
}
return x;
}
Run Code Online (Sandbox Code Playgroud)
一切都很好,现在问题是函数的输出,即
> erase_zero(c(0,1,2,3,0))
[1] 1 2 3
> erase_zero(c(0,0,1,2,3,0,0))
[1] 0 1 2 3 0
> erase_zero(c(0,0,0,1,2,3,0,0,0))
[1] 0 1 2 3 0
> erase_zero(c(0,0,0,0,1,2,3,0,0,0,0))
[1] 0 0 1 2 3 0 0
Run Code Online (Sandbox Code Playgroud)
我不知道为什么会发生这种情况。
阅读下面的所有答案后,我只是尝试了速度测试
> microbenchmark(erase_zero(s), erase_zero1(s), erase_zero_sugar(s))
Unit: microseconds
expr min lq …Run Code Online (Sandbox Code Playgroud)