ruby2.1 prime.rb
def susu(n)
result=[];
for i in 2..n do
f=true
limit=(i**0.5+1).to_i;
for j in 2..limitdo
if i % j ==0 then
f=false;break;
end
end
if(f) then
result.push(i);
end
end
return result
end
start = Time.new
out= susu(10000)
puts (Time.new-start).to_f
# puts out.length
nodejs v0.10.31 prime.js
function sushu(n){
var result=[];
for(var i=2;i<=n;i++){
var f=true;
var limit=parseInt( Math.pow(i,0.5)+1);
for(var j=2;j<=limit;j++){
if (i%j==0){
f=false;
break;
}
}
if (f){
result.push(i);
}
}
return result;//#print_r($result);
}
var start=(new Date()).getTime();
var b=sushu(10000);
console.log( ((new Date()).getTime()-start)/1000);
运行时间
测试程序
h={:ruby=>'prime.rb',:node=>'prime.js'}
result={}
h.map { |k,v| result[k]=[] }
h.each do |runtime,file|
cmd=" #{runtime} #{file} "
(1..10).each do |runs |
#puts cmd
IO.popen(cmd) do |f| time= f.gets
result[runtime].push(time.chomp.to_f)
end
end
end
puts result
result.each do |lang,total|
print lang,9.chr, total.inject{ |sum, el| sum + el }.to_f / total.size,10.chr
end
运行结果 ruby 0.027541700000000002 node 0.0215
ruby 和 nodejs 速度相关并不大