gpt4 book ai didi

r - 如何改进这个哈希函数

转载 作者:行者123 更新时间:2023-12-04 10:48:53 24 4
gpt4 key购买 nike

有没有办法提高这个散列的初始化速度?目前,这在我的机器上大约需要 20 分钟。

#prepare hash()
hash <- list();

mappedV <- # matrix with more than 200,000 elements
for( i in 1:nrow(mappedV) ) {
hash[[paste(mappedV[i,], collapse = '.')]] <- 0;
}

在这段代码之前,我使用了一个矩阵,但这花了我3个多小时。所以我不会提示这 20 分钟。我只是好奇是否有更好的选择。我使用哈希函数对 200,000 种可能组合中的每一种进行计数。

PS:并发可能是一种选择。但这并没有改进散列。

最佳答案

通过预先分配所需长度的列表而不是在每次迭代时增加列表,您通常会节省大量时间。

看:

X <- vector(mode="list", 1e5)
Y <- list()

system.time(for(i in 1:1e5) X[[i]] <- 0)
# user system elapsed
# 0.3 0.0 0.3
system.time(for(i in 1:1e5) Y[[i]] <- 0)
# user system elapsed
# 48.84 0.05 49.34
identical(X,Y)
# [1] TRUE

因为整个列表 Y 每次被添加时都会被复制,添加额外的元素只会随着大小的增长而变得越来越慢。

关于r - 如何改进这个哈希函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14914965/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com