测试一下本地js、浏览器中的js以及ruby对于类似算法的性能。结果有些意外:浏览器js最快,本地其次当相差很小;ruby最慢而且不是一个数量级的;
因为写的匆忙,可能有重大问题没能看出来,请各位高人不吝赐教。
程序计算小于给定数n的最大素数,代码均未作优化,我们依次来看:
首先是浏览器的:
<!DOCTYPE html>
<html>
<head>
<title>sieve suanfa</title>
<script src="sieve.js" type="text/javascript"></script>
<script type="text/javascript">
window.onload = function(){
btn_n.onclick = function(){
var i = parseInt(n.value);
if(isNaN(i))
result.innerHTML = "must input a number";
else if(i <= 0)
result.innerHTML = "must input + number";
else{
var start = new Date().getTime();
var max_p = sieve(i);
var spend = new Date().getTime() - start;
result.innerHTML = "max_p is : " + max_p + "(take " + spend + "ms)";
}
}
}
</script>
<style type="text/css">
#result{
color: red;
font-weight: bold;
}
</style>
</head>
<body>
<h1>Sieve Suanfa</h1>
<label for="n">input n : </label>
<input type="text" id="n" />
<input type="button" id="btn_n" value="ret max p" />
<label id="result"></label>
</body>
</html>
其中的sieve函数和下面的sieve一致。计算1千万300ms左右,1亿4000ms左右
下面是node.js本地的测试:
#!/usr/bin/node
var path = require("path");
//return max su shu but < n
function sieve(n){
var a = new Int8Array(n+1);
var max = Math.floor(Math.sqrt(n));
var p = 2;
while(p <= max){
for(var i=2*p;i<=n;i+=p)
a[i] = 1;
while(a[++p]); /* empty */
}
while(a[n]) n--;
return n;
}
//0:node , 1:sieve_node.js , 2:n
if(process.argv.length < 3){
console.log("must input n value like : " + path.basename(process.argv[1]) + " 1000");
return;
}
var i = parseInt(process.argv[2]);
if(isNaN(i))
console.log("must input a number");
else if(i < 0)
console.log("must input + number");
else{
var start = new Date().getTime();
var max_p = sieve(i);
var end = new Date().getTime() - start;
console.log("max p is " + max_p + "(take " + end + " ms)");
}
测试结果和浏览器js类似,不过前者在多次计算1亿后会发生脚本无响应的情况,后者一直很稳定。
最后是ruby的测试:
#!/usr/local/bin/ruby
def sieve(n)
a = Array.new(n+1);
max = Math.sqrt(n).to_i;
p = 2;
while p<=max do
i = 2*p
while i<=n do
a[i] = 1
i+=p
end
while a[p+=1] == 1 do end
end
while a[n] do n-=1 end
n
end
x = ARGV[0].to_i
if x == 0
puts "must input a number"
elsif x < 0
puts "must input + number"
else
start = Time.now.to_f
max_p = sieve(x)
_end = Time.now.to_f - start
puts "max p is #{max_p} (take #{_end*1000} ms)"
end
计算1千万将近2秒,1亿超过20秒。当然ruby肯定有优化空间,在这里不展开发挥了。