我想看看 julia 语言,所以我写了一个小脚本来导入我正在使用的数据集。但是当我运行并分析脚本时,结果发现它比 R 中的类似脚本慢得多。
当我进行分析时,它告诉我所有 cat 命令的性能都很差。
文件如下所示:
#
#Metadata
#
Identifier1 data_string1
Identifier2 data_string2
Identifier3 data_string3
Identifier4 data_string4
//
我主要想获取 data_strings 并将它们分成单个字符的矩阵。
这是一个以某种方式最小的代码示例:
function loadfile()
f = open("/file1")
first=true
m = Array(Any, 1,0)
for ln in eachline(f)
if ln[1] != '#' && ln[1] != '\n' && ln[1] != '/'
s = split(ln[1:end-1])
s = split(s[2],"")
if first
m = reshape(s,1,length(s))
first = false
else
s = reshape(s,1,length(s))
println(size(m))
println(size(s))
m = vcat(m, s)
end
end
end
end
知道为什么 julia 使用 cat 命令可能会很慢,或者我可以如何做?
感谢您的任何建议!
最佳答案
像这样使用 cat
很慢,因为它需要大量的内存分配。每次我们执行 vcat
时,我们都会分配一个全新的数组 m
,它与旧的 m
大致相同。以下是我如何以更儒略的方式重写您的代码,其中 m
仅在最后创建:
function loadfile2()
f = open("./sotest.txt","r")
first = true
lines = Any[]
for ln in eachline(f)
if ln[1] == '#' || ln[1] == '\n' || ln[1] == '/'
continue
end
data_str = split(ln[1:end-1]," ")[2]
data_chars = split(data_str,"")
# Can make even faster (2x in my tests) with
# data_chars = [data_str[i] for i in 1:length(data_str)]
# But this inherently assumes ASCII data
push!(lines, data_chars)
end
m = hcat(lines...)' # Stick column vectors together then transpose
end
我制作了您的示例数据的 10,000 行版本,并发现以下性能:
Old version:
elapsed time: 3.937826405 seconds (3900659448 bytes allocated, 43.81% gc time)
elapsed time: 3.581752309 seconds (3900645648 bytes allocated, 36.02% gc time)
elapsed time: 3.57753696 seconds (3900645648 bytes allocated, 37.52% gc time)
New version:
elapsed time: 0.010351067 seconds (11568448 bytes allocated)
elapsed time: 0.011136188 seconds (11568448 bytes allocated)
elapsed time: 0.010654002 seconds (11568448 bytes allocated)
关于Julia 使用 cat 命令很慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28539382/