我编写了一个快速的 Python 脚本来比较两个文件,每个文件都包含无序的哈希值,以验证两个文件除了顺序之外是否相同。然后出于教育目的,我用 Ruby 重写了它。
Python 实现需要几秒钟,而 Ruby 实现大约需要 4 分钟。
我觉得这很可能是因为我缺乏 Ruby 知识,对我做错了什么有什么想法吗?
环境是 Windows XP x64、Python 2.6、Ruby 1.8.6
python
f = open('c:\\file1.txt', 'r')
hashes = dict()
for line in f.readlines():
if not line in hashes:
hashes[line] = 1
else:
hashes[line] += 1
print "Done file 1"
f.close()
f = open('c:\\file2.txt', 'r')
for line in f.readlines():
if not line in hashes:
print "Hash not found!"
else:
hashes[line] -= 1
f.close()
print "Done file 2"
num_errors = 0
for key in hashes.keys():
if hashes[key] != 0:
print "Uneven hash count: %s" % key
num_errors += 1
print "Total of %d mismatches found" % num_errors
ruby
file = File.open("c:\\file1.txt", "r")
hashes = {}
file.each_line { |line|
if hashes.has_key?(line)
hashes[line] += 1
else
hashes[line] = 1
end
}
file.close()
puts "Done file 1"
file = File.open("c:\\file2.txt", "r")
file.each_line { |line|
if hashes.has_key?(line)
hashes[line] -= 1
else
puts "Hash not found!"
end
}
file.close()
puts "Done file 2"
num_errors = 0
hashes.each_key{ |key|
if hashes[key] != 0
num_errors += 1
end
}
puts "Total of #{num_errors} mismatches found"
编辑 为了给出规模的概念,每个文件都非常大,超过 900 000 个哈希值。
进展
使用 nathanvda 的建议,这是优化的 ruby 脚本:
f1 = "c:\\file1.txt"
f2 = "c:\\file2.txt"
hashes = Hash.new(0)
File.open(f1, "r") do |f|
while line = f.gets
hashes[line] += 1
end
end
not_founds = 0
File.open(f2, "r") do |f|
while line = f.gets
if hashes.has_key?(line)
hashes[line] -= 1
else
not_founds += 1
end
end
end
num_errors = hashes.values.to_a.select { |z| z != 0}.size
puts "Total of #{not_founds} lines not found in file2"
puts "Total of #{num_errors} mismatches found"
在带有 Ruby 1.8.7 的 Windows 上,原始版本耗时 250 秒,优化版本耗时 223。
在 Linux 虚拟机上!运行 ruby 1.9.1,原始版本运行时间为 81 秒,大约是 windows 1.8.7 的 1/3。有趣的是,优化后的版本耗时更长,为 89 秒。请注意,由于内存限制,while line = ... 是必需的。
在带有 Ruby 1.9.1 的 Windows 上,原始版本耗时 457 秒,优化版本耗时 543 秒。
在带有 jRuby 的 windows 上,原始版本需要 45 秒,优化版本需要 43 秒。
我对结果有些惊讶,我预计 1.9.1 会比 1.8.7 有所改进。
最佳答案
我发现 Ruby 的引用实现(好吧,Ruby)是(不科学地)狗慢。
如果有机会,请尝试在 JRuby 下运行您的程序! Charles Nutter 和其他 Sun 人员声称已经大大加快了 Ruby 的速度。
我个人对您的结果最感兴趣。
关于python - 执行速度差异的原因是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1863724/