4

我正在尝试使用 RcppParallel 并行化(大)向量的添加。这就是我想出的。

// [[Rcpp::depends(RcppParallel)]]
#include <RcppParallel.h>
#include <Rcpp.h>
#include <assert.h> 
using namespace RcppParallel;
using namespace Rcpp;

// [[Rcpp::export]]
NumericVector directVectorAddition(NumericVector first, NumericVector second) {
    assert (first.length() == second.length());
    NumericVector results(first.length());
    results = first + second;
    return results;
}

// [[Rcpp::export]]
NumericVector loopVectorAddition(NumericVector first, NumericVector second) {
    assert (first.length() == second.length());
    NumericVector results(first.length());
    for(unsigned i = 0; i != first.length(); i++)
        results[i] = first[i] + second[i];
    return results;
}

struct VectorAddition : public Worker
{
    const RVector<double> first, second;
    RVector<double> results;
    VectorAddition(const NumericVector one, const NumericVector two, NumericVector three) : first(one), second(two), results(three) {}

    void operator()(std::size_t a1, std::size_t a2) {
        std::transform(first.begin() + a1, first.begin() + a2,
                       second.begin() + a1,
                       results.begin() + a1,
                       [](double i, double j) {return i + j;});
    }
};


// [[Rcpp::export]]
NumericVector parallelVectorAddition(NumericVector first, NumericVector second) {
    assert (first.length() == second.length());
    NumericVector results(first.length());
    VectorAddition myVectorAddition(first, second, results);
    parallelFor(0, first.length(), myVectorAddition);
    return results;
}

它似乎可以工作,但不能加快速度(至少在 4 核机器上不行)。

> v1 <- 1:1000000
> v2 <- 1000000:1
> all(directVectorAddition(v1, v2) == loopVectorAddition(v1, v2))
[1] TRUE
> all(directVectorAddition(v1, v2) == parallelVectorAddition(v1, v2))
[1] TRUE
> result <- benchmark(v1 + v2, directVectorAddition(v1, v2), loopVectorAddition(v1, v2), parallelVectorAddition(v1, v2), order="relative")
 > result[,1:4]
                            test replications elapsed relative
    1                        v1 + v2          100   0.206    1.000
    4 parallelVectorAddition(v1, v2)          100   0.993    4.820
    2   directVectorAddition(v1, v2)          100   1.015    4.927
    3     loopVectorAddition(v1, v2)          100   1.056    5.126

这可以更有效地实施吗?

非常感谢提前,

mce

4

1 回答 1

5

菜鸟错误:) 您将其定义为Rcpp::NumericVector但创建通过序列运算符创建的数据。这会创建数值,因此您将强制复制到所有函数上!

做了

v1 <- as.double(1:1000000)
v2 <- as.double(1000000:1)

相反,在一台有很多内核的机器上(在工作中)我然后看到

R> result[,1:4]
                            test replications elapsed relative
4 parallelVectorAddition(v1, v2)          100   0.301    1.000
2   directVectorAddition(v1, v2)          100   0.424    1.409
1                        v1 + v2          100   0.436    1.449
3     loopVectorAddition(v1, v2)          100   0.736    2.445

这个例子仍然没有那么令人印象深刻,因为相关操作是“便宜的”,而并行方法需要分配内存,将数据复制到工作人员,再次收集等等。

但好消息是您正确编写了并行代码。不是一个小任务。

于 2018-11-09T21:41:41.593 回答