How could I speed up this Rcpp code?

后端 未结 1 1906
情歌与酒
情歌与酒 2021-01-03 17:31

I had implemented a function in R which was long to run. I have succeeded in improving it in R but now I would like to speed it up more by using Rcpp package.

I have

1条回答
  •  别那么骄傲
    2021-01-03 18:07

    Since I do not exactly know what your code does, I can see two things from the scratch:

    • The function you call from your R environment is testFromontcpp(...). I suggest that this function should have SEXP values as parameters. Those S-Expressions are pointer to the memory of R. If you don't use SEXP, then both matrices will be copied: Consider a 1000x1000 matrix, this means you have 1 million entries saved in R, which are copied to C++. To do so write:

      testFromontcpp(SEXP x, SEXP y, SEXP z) {

      NumericMatrix z1(x), z2(y);

      int *Nbootstrap = INTEGER(z);

      ... }

    Be careful: In the for-loop you cannot use i. You have to write i<*Nbootstrap!!!

    • Secondly...and more important: Since R's matrices are saved as pointer to column and from the column pointer to the row, C's matrices are saved the other way round. What I want to say is that it costs a lot to jump into memory and jump back the whole time instead of following the memory path. My suggestion for this is: Switch the for-loops, so first iterate over the row of a specific column and not the other way round.

    To the last point: In a task at university I had the problem with iterating over matrices, too. In my case it was way cheaper to transpose the matrix and then do calculations.

    I hope I could help you.

    Best, Michael

    PS: Referring to point 1...I just benchmarked your code with your implementation and with using SEXP. With SEXP it is slightly quicker for a 100x100 matrix with random numbers between 1 to 10.

    0 讨论(0)
提交回复
热议问题