Guest User

Untitled

a guest
Jul 19th, 2018
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.08 KB | None | 0 0
  1. library('microbenchmark')
  2. library('Rcpp')
  3. library('RcppParallel')
  4. library('foreach')
  5. library('doParallel')
  6. library('iterators')
  7.  
  8. sourceCpp('testrcpp.cpp')
  9.  
  10. ##~~~~~~~~~~~~~~~~~~~R parallel~~~~~~~~~~~~~~~~~
  11. SqrtRPara <- function(orig, n = 8) {
  12.  
  13. registerDoParallel(cores = n)
  14.  
  15. itx <- iter(orig)
  16.  
  17. res <- foreach(i = itx, .combine = c) %dopar% {
  18. return(sqrt(i))
  19. }
  20.  
  21. ## stop multiple cores
  22. stopImplicitCluster()
  23.  
  24. return(res)
  25. }
  26.  
  27. SqrtR <- function(orig) {
  28.  
  29. res <- numeric(length(orig))
  30.  
  31. for (i in orig) {
  32. res[i] <- sqrt(orig[i])
  33. }
  34.  
  35. return(res)
  36.  
  37. }
  38. ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  39.  
  40. ##~~~~~~~~~~~~~~~~test~~~~~~~~~~~~~~~~~~~~~
  41. tmp1 <- runif(10e3)
  42.  
  43. all.equal(SqrtCpp(tmp1),
  44. sqrt(tmp1),
  45. SqrtCppPara(tmp1))
  46.  
  47. microbenchmark(
  48. SqrtCpp(tmp1),
  49. sqrt(tmp1),
  50. SqrtCppPara(tmp1)
  51. )
  52.  
  53. all.equal(SqrtCpp(tmp1),
  54. sqrt(tmp1),
  55. SqrtR(tmp1),
  56. SqrtRPara(tmp1),
  57. SqrtCppPara(tmp1))
  58.  
  59. microbenchmark(
  60. SqrtCpp(tmp1),
  61. sqrt(tmp1),
  62. SqrtRPara(tmp1),
  63. SqrtR(tmp1),
  64. SqrtCppPara(tmp1)
  65. )
  66. ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Add Comment
Please, Sign In to add comment