R에서 병렬화

R의 병렬 프로그래밍

Nabeel Imam

Data Scientist

실전 예시

데이터

print(file_list)
 [1] "./uni_data_country/Argentina.csv"
 [2] "./uni_data_country/Armenia.csv"
 [3] "./uni_data_country/Australia.csv"
 [4] "./uni_data_country/Austria.csv"
 [5] "./uni_data_country/Azerbaijan.csv"
 [6] "./uni_data_country/Bahrain.csv"
 [7] "./uni_data_country/Bangladesh.csv"
 [8] "./uni_data_country/Belarus.csv"
 [9] "./uni_data_country/Belgium.csv"
[10] "./uni_data_country/Bolivia.csv"
...

세 개의 대학 건물과 졸업생이 보이며, 각각 1~3위 순위가 매겨져 있습니다.

R의 병렬 프로그래밍

열 추가하기

for (file in file_list) {

  df <- read.csv(file)


df$top100 <- NA for (r in 1:nrow(df)) { df$top100[r] <- df$world_rank[r] <= 100 }
write.csv(df, file) }
R의 병렬 프로그래밍

프로파일링

코드

library(profvis)


profvis({
for (file in file_list) { df <- read.csv(file) df$top100 <- NA for (r in 1:nrow(df)) { df$top100[r] <- df$Rank[r] <= 100 } write.csv(df, file) }
})

출력

profvis() 프로파일링 결과. 예제 코드에서 데이터 읽기는 40ms, `top100` 열 채우기는 80ms가 소요됩니다. 다른 단계는 거의 즉시 완료됩니다.

R의 병렬 프로그래밍

병렬화해 봅시다

루프

  for (file in file_list) {

    df <- read.csv(file)
    df$top100 <- NA

    for (r in 1:nrow(df)) {
      df$top100[r] <- df$Rank[r] <= 100
    }
    write.csv(df, file)
  }

함수

add_col <- function(file_path) {

  df <- read.csv(file_path)
  df$top100 <- NA

  for (r in 1:nrow(df)) {
    df$top100[r] <- df$Rank[r] <= 100
  }
  write.csv(df, file_path)
}


cl <- makeCluster(6)
dummy <- parLapply(cl, file_list, add_col) stopCluster(cl)
R의 병렬 프로그래밍

실무 고려 사항: 코어 수

코어 감지

detectCores()
[1] 8

병렬 코드

cl <- makeCluster(detectCores() - 2)


dummy <- parLapply(cl, file_list, add_col) stopCluster(cl)
R의 병렬 프로그래밍

실무 고려 사항: 클러스터 유형

PSOCK 클러스터(기본)

cl <- makeCluster(detectCores() - 2)
  • 현재 R 세션의 복사본을 생성
  • 코어 간 메모리 비공유
  • 모든 OS에서 동작(Windows, Mac, Linux)

FORK 클러스터

cl <- makeCluster(detectCores() - 2,
                  type = "FORK")
  • R 세션에서 하위 프로세스 생성
  • 코어 간 메모리 공유(PSOCK보다 빠름)
  • Windows에서는 미지원
R의 병렬 프로그래밍

실습해 봅시다!

R의 병렬 프로그래밍

Preparing Video For Download...