Song song hóa trong R

Lập trình song song trong R

Nabeel Imam

Data Scientist

Ví dụ thực tế

Dữ liệu

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"
...

Ba tòa nhà đại học với sinh viên tốt nghiệp, mỗi tòa có thứ hạng từ một đến ba.

Lập trình song song trong R

Thêm một cột

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) }
Lập trình song song trong R

Profiling

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) }
})

Kết quả

Kết quả profiling từ profvis(). Với mã mẫu, đọc dữ liệu mất 40 mili-giây, điền giá trị cột `top100` mất 80 mili-giây. Các bước khác gần như tức thời.

Lập trình song song trong R

Hãy song song hóa

Vòng lặp

  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)
  }

Hàm

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)
Lập trình song song trong R

Lưu ý thực tế: số lõi

Phát hiện số lõi

detectCores()
[1] 8

Mã hóa song song

cl <- makeCluster(detectCores() - 2)


dummy <- parLapply(cl, file_list, add_col) stopCluster(cl)
Lập trình song song trong R

Lưu ý thực tế: loại cụm

Cụm PSOCK (mặc định)

cl <- makeCluster(detectCores() - 2)
  • Tạo bản sao phiên R hiện tại
  • Lõi không dùng chung bộ nhớ
  • Hoạt động trên mọi HĐH (Windows, Mac, Linux)

Cụm FORK

cl <- makeCluster(detectCores() - 2,
                  type = "FORK")
  • Tạo tiến trình con từ phiên R
  • Lõi dùng chung bộ nhớ (nhanh hơn PSOCK)
  • Không hoạt động trên Windows
Lập trình song song trong R

Hãy luyện tập!

Lập trình song song trong R

Preparing Video For Download...