假设我有一个8核CPU。在R中使用doParallel
,当我注册makeCluster(x)
时,要使用的理想核心数x
是多少?
是否尽可能多的内核?或者使用7核比使用6核慢?对此有什么规定吗?
答案 0 :(得分:0)
如评论中所述,最佳内核数量取决于手头的任务,但您可以自己找到。初始化7个不同的群集,并对结果进行基准测试。我不会使用所有8个内核,因此您的情况下最多应使用7个内核。
这是一个小的“傻”模板,其中并行化没有意义,因为简单的sapply版本要快得多,因为发送到内核的开销会大大降低性能。
无论如何,插入您要优化的代码,试一试并找到理想的设置;)
require(parallel)
cl2 = makeCluster(2)
cl3 = makeCluster(3)
cl4 = makeCluster(4)
cl5 = makeCluster(5)
cl6 = makeCluster(6)
cl7 = makeCluster(7)
library(microbenchmark)
mc <- microbenchmark(times = 100,
noPa = {
res = sapply(mtcars, mean, na.rm = TRUE)
},
cor2 = {
res = parSapply(cl2, mtcars, mean, na.rm = TRUE)
},
cor3 = {
res = parSapply(cl3, mtcars, mean, na.rm = TRUE)
},
cor4 = {
res = parSapply(cl4, mtcars, mean, na.rm = TRUE)
},
cor5 = {
res = parSapply(cl5, mtcars, mean, na.rm = TRUE)
},
cor6 = {
res = parSapply(cl6, mtcars, mean, na.rm = TRUE)
},
cor7 = {
res = parSapply(cl7, mtcars, mean, na.rm = TRUE)
}
); mc
stopCluster(cl2);stopCluster(cl3);stopCluster(cl4);
stopCluster(cl5);stopCluster(cl6);stopCluster(cl7)
Unit: microseconds expr min lq mean median uq max neval noPa 77.370 94.4365 97.52549 97.281 101.5475 131.983 100 cor2 713.388 804.1260 947.56529 836.553 887.4680 7178.812 100 cor3 840.250 941.2275 1071.55460 967.681 1027.4145 5343.576 100 cor4 877.797 1046.7570 1194.51996 1077.761 1132.3745 7028.057 100 cor5 1032.535 1139.2015 1303.64424 1190.686 1241.3170 8148.199 100 cor6 1141.761 1222.5430 1438.18655 1261.797 1339.1655 10589.302 100 cor7 1269.192 1345.4240 1586.03513 1399.468 1487.3615 10547.204 100
在这里是一个并行化示例。根据结果,7个内核将是最快的解决方案。如果您在自己的计算机上运行它,并且想在它旁边做其他事情,那么我会选择4个内核,因为时间可比,并且计算机无法以最大容量运行。
library(lme4)
f <- function(i) {
lmer(Petal.Width ~ . - Species + (1 | Species), data = iris)
}
library(microbenchmark)
mc <- microbenchmark(times = 3,
noPa = {
res = sapply(1:100, f)
},
cor2 = {
res = parSapply(cl2, 1:100, f)
},
cor3 = {
res = parSapply(cl3, 1:100, f)
},
cor4 = {
res = parSapply(cl4, 1:100, f)
},
cor5 = {
res = parSapply(cl5, 1:100, f)
},
cor6 = {
res = parSapply(cl6, 1:100, f)
},
cor7 = {
res = parSapply(cl7, 1:100, f)
}
); mc
Unit: milliseconds expr min lq mean median uq max neval noPa 1925.2889 1964.9473 2169.9294 2004.6057 2292.250 2579.894 3 cor2 1501.8176 1591.5596 1722.1834 1681.3015 1832.366 1983.431 3 cor3 1097.4251 1188.6271 1345.1643 1279.8291 1469.034 1658.239 3 cor4 956.9829 1007.6607 1302.2984 1058.3384 1474.956 1891.574 3 cor5 1027.5877 1872.3501 2379.9384 2717.1125 3056.114 3395.115 3 cor6 1001.2572 1048.8277 1217.5999 1096.3983 1325.771 1555.144 3 cor7 815.2055 905.7948 945.7555 996.3841 1011.030 1025.677 3