Big*_*ing 3 ruby arrays hash compare
我绝对是ruby的新手(并使用1.9.1),所以任何帮助都表示赞赏.我所学到的关于Ruby的一切都来自谷歌.我正在尝试比较两个哈希数组,并且由于它们的大小,它已经让位于长时间并且因内存耗尽而调情.任何帮助,将不胜感激.
我有一个Class(ParseCSV),有多种方法(初始化,打开,比较,剥离,输出).我现在使用它的方式如下(这确实通过了我编写的测试,只使用了更小的数据集):
file1 = ParseCSV.new(“some_file”)
file2 = ParseCSV.new(“some_other_file”)
file1.open #this reads the file contents into an Array of Hash’s through the CSV library
file1.strip #This is just removing extra hash’s from each array index. So normally there are fifty hash’s in each array index, this is just done to help reduce memory consumption.
file2.open
file2.compare(“file1.storage”) #@storage is The array of hash’s from the open method
file2.output
Run Code Online (Sandbox Code Playgroud)
现在我正在努力的是比较方法.处理较小的数据集根本不是什么大问题,工作得足够快.然而,在这种情况下,我将大约400,000条记录(全部读入哈希数组)与具有大约450,000条记录的记录进行比较.我正试着加快速度.另外,我无法在file2上运行strip方法.我现在就是这样做的:
def compare(x)
#obviously just a verbose message
puts "Comparing and leaving behind non matching entries"
x.each do |row|
#@storage is the array of hashes
@storage.each_index do |y|
if row[@opts[:field]] == @storage[y][@opts[:field]]
@storage.delete_at(y)
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
希望这是有道理的.我知道这将是一个缓慢的过程,因为它必须每次迭代400,000行440,000次.但是,您对如何加速并可能减少内存消耗有任何其他想法吗?
哎呀,这将是O(n)平方运行时间.讨厌.
更好的选择是使用内置的Set类.
代码看起来像:
require 'set'
file1_content = load_file_content_into_array_here("some_file")
file2_content = load_file_content_into_array_here("some_other_file")
file1_set = Set[file1_content]
unique_elements = file1_set - file2_content
Run Code Online (Sandbox Code Playgroud)
这假设文件本身具有独特的内容.应该在通用情况下工作,但可能有怪癖取决于你的数据是什么样的以及你如何解析它,但只要行可以与==它进行比较应该可以帮助你.
使用集合比执行嵌套循环迭代文件内容要快得多.
(是的,其实我已经做到了这一点,以处理与约2个百万行的文件,所以它应该能够处理您的案件 - 最终如果你正在做大量的数据改写(munging),红宝石可能不是工具的最佳选择,虽然)
| 归档时间: |
|
| 查看次数: |
5535 次 |
| 最近记录: |