gpt4 book ai didi

r - 带替换件的快速排序样本

转载 作者:行者123 更新时间:2023-12-04 11:56:14 24 4
gpt4 key购买 nike

基本上,我想做sort(sample(n, replace = TRUE)) , 为 n = 1e6 , 并且多次(例如 1e4 次)。

有什么办法可以在 R(cpp) 中更快地做到这一点?

最佳答案

在 Rcpp 中实现@Frank 的想法:

#include <Rcpp.h>
using namespace Rcpp;

// [[Rcpp::export]]
IntegerVector sort_sample(int n) {
IntegerVector tab(n);
for (int i = 0; i < n; i++) {
int k = n * unif_rand();
tab[k]++;
}
return tab;
}

基准:
microbenchmark::microbenchmark(
sort(sample(n, replace = TRUE)),
tabulate(sample(n, replace = TRUE), n),
sort_sample(n)
)

对于 n = 1e5:
Unit: microseconds
expr min lq mean median uq max neval
sort(sample(n, replace = TRUE)) 3214.726 3393.606 3667.1001 3507.0525 3716.3560 7007.411 100
tabulate(sample(n, replace = TRUE), n) 1087.543 1104.215 1245.0722 1136.9085 1218.5865 4265.075 100
sort_sample(n) 789.403 812.780 870.2723 837.3445 924.4395 1188.432 100

对于 n = 1e6:
Unit: milliseconds
expr min lq mean median uq max neval
sort(sample(n, replace = TRUE)) 49.96651 52.58784 61.19775 55.09312 58.43035 160.16275 100
tabulate(sample(n, replace = TRUE), n) 13.74391 14.44253 17.22742 15.99816 17.54367 48.72374 100
sort_sample(n) 12.80741 14.40371 17.98320 15.31699 17.53548 63.21692 100

关于r - 带替换件的快速排序样本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56779135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com