# Parallel processing in R

In R a lot of operations will take advantage of parallel processing, provided the BLAS being used supports it. As in python it’s also possible to manually split calculations up between multiple cores. The code below uses the `doParallel` package and a `foreach` loop combined with `%dopar%` to split up a matrix multiplication task. If I limit the BLAS to using one thread, this will speed up the calculation. This sort of construction could also be used to run independent simulations.

I think this is a lot more intuitive than the parallel python implementation (see post). I’m curious to look at other parallel processing python modules to see how they compare.

```require(parallel)
require(doParallel)
library(foreach)
library(iterators)

parFun <- function(A, B){
A%*%B
}

nCores <- 2
n <- 4000 # for this toy code, make sure n is divisible by nCores
a <- rnorm(n*n)
A <- matrix(a, ncol=n)

registerDoParallel(nCores)
systime <- system.time(
result <- foreach(i = 1:nCores, .combine = cbind) %dopar% {
rows <-  ((i - 1)*n/nCores + 1):(i*n/nCores)
out <- parFun(A, A[, rows])
}
)

print(paste("Cores = ", nCores))
print(systime)
```
{"ft_lang_label":"__label__en","ft_lang_prob":0.74361503,"math_prob":0.9670172,"size":1118,"snap":"2021-43-2021-49","text_gpt3_token_len":291,"char_repetition_ratio":0.10502693,"word_repetition_ratio":0.0,"special_character_ratio":0.25849733,"punctuation_ratio":0.09803922,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.9936091,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2021-10-17T20:00:48Z\",\"WARC-Record-ID\":\"<urn:uuid:0d781ff9-615b-4998-81af-ec76d2f7817e>\",\"Content-Length\":\"34716\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:d929e1f1-cddc-40be-aa37-5c8dcd58d839>\",\"WARC-Concurrent-To\":\"<urn:uuid:19761bae-d8ea-413d-ba34-3be281dd5656>\",\"WARC-IP-Address\":\"208.94.116.70\",\"WARC-Target-URI\":\"https://www.frankcleary.com/tag/r/\",\"WARC-Payload-Digest\":\"sha1:MWOBXKMAWCSAYR27SODS33BY5Y3VOXZB\",\"WARC-Block-Digest\":\"sha1:E2BSNFGW5C4HHG5CU3JNTSL3SQGOCT4F\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2021/CC-MAIN-2021-43/CC-MAIN-2021-43_segments_1634323585181.6_warc_CC-MAIN-20211017175237-20211017205237-00551.warc.gz\"}"}