这里有一个简单的例子:
#Load libraries:
library(data.table)
library(tictoc)
#Set the number of threads:
setDTthreads(1)
#Set seed:
set.seed(1)
#Create a small example:
n_f<-2500
n_w<-sample(1:1000,n_f,replace=TRUE)
n_t<-sample(c("","AS","E","D","F"),n_f,replace=TRUE)
yearmonth<-ifelse(nchar(seq(1,12))==1,paste("0",seq(1,12),sep=""),seq(1,12))
yearmonth<-paste(rep(seq(1996,2018),each=12),yearmonth,sep="")
#Create a large synthetic data set:
data_final<-list("vector")
for (i in 1:length(yearmonth)){
data_aux<-data.table(fid=rep(1:n_f,n_w),type=rep(n_t,n_w),date=yearmonth[i])
data_final[[i]]<-data_aux
}
#Combine everything together:
data_final<-rbindlist(data_final)
#Do the calculation:
tic()
data_final[,nr_unique_type:=uniqueN(type),by=c("fid","date")]
toc()
在我的机器上,计算大约需要23秒。另一方面,如果我未指定setDTthreads(1)(它使用32个内核),则它将运行53秒。也许有人可以解释为什么使用多线程会这么慢。
我正在使用
R 3.6.0
和data.table 1.12.8
最佳答案
根据评论中的讨论。这是已知的效率低下,即使在计算相对较小的任务时,也会由于组成一组CPU线程而导致效率低下。
最新版本的data.table(1.12.10)中对此进行了改进。
OP已经对此进行了验证。
不再需要使用setDTthreads(1)
来避免这种低效率。
关于r - R中的多线程数据表比使用单线程的慢得多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62347788/