问题 1:为啥多线程比单线程慢这么多(大约 1 分钟)? 问题 2:为啥 Ruby 的 MD5 计算这么慢?同样的单线程版程序我用 php/go 写都只用大约 1 分钟。难道我使用不对?
多线程版:
#!/usr/bin/ruby
require 'digest/md5'
def fexe(value="")
digest = Digest::MD5.hexdigest(value)
for i in 1..10000
digest = Digest::MD5.hexdigest(value)
end
end
count = 0
arr = []
msg = "http://php.net/manual/en/function.printf.php";
for i in 1..10000
arr[i-1] = Thread.new {
fexe(msg)
}
end
puts "size: #{arr.size}"
arr.each {|t| t.join; }
puts "done!"
输出:
size: 10000
done!
real 5m27.146s
user 5m19.881s
sys 0m2.870s
单线程版:
#!/usr/bin/ruby
require 'digest/md5'
def fexe(value="")
digest = Digest::MD5.hexdigest(value)
for i in 1..10000
digest = Digest::MD5.hexdigest(value)
end
end
count = 0
arr = []
msg = "http://php.net/manual/en/function.printf.php";
for i in 1..10000
fexe(msg)
end
puts "size: #{arr.size}"
puts "done!"
输出:
size: 0
done!
real 4m16.798s
user 4m16.175s
sys 0m0.189s