Skip to content

Instantly share code, notes, and snippets.

@BeRo1985
Last active Jun 12, 2016
Embed
What would you like to do?
POCA vs Lua benchmark
d:\Projects\POCA\trunk\src>lua53.exe primes.lua
time: 0.18200000 seconds, primes: 17984.000000
time: 54.92000000 seconds, primes: 17984.000000
time: 50.26400000 seconds, primes: 17984.000000
d:\Projects\POCA\trunk\src>pocarun primes.poca
time: 0.032 seconds, primes: 17984
time: 14.741 seconds, primes: 17984
time: 13.948 seconds, primes: 17984
function searchPrimes(from, to)
local dummy = 0
local primes = 0
local n = 0
local i = 0
local j = 0
local isPrime = 0
for n = from, to do
if ((n % 2) == 0) then
i = 2
else
i = 3
end
j = math.sqrt(n)
isPrime = 1
while i <= j do
if ((n % i) == 0) then
isPrime = 0
break
end
i = i + 2
end
primes = primes + isPrime
end
return primes
end
function isprime(n)
for i = 2, (n - 1) do
if (n % i == 0) then
return false
end
end
return true
end
function primes(n)
local count = 0
for i = 2, n do
if (isprime(i)) then
count = count + 1
end
end
return count
end
function primes2(n)
local count = 0
local isPrime = 0
local i = 0
local j = 0
for i = 2, n do
isPrime = 1;
for j = 2, (i - 1) do
if ((i % j) == 0) then
isPrime = 0;
break;
end
end
count = count + isPrime;
end
return count
end
local N = 200000
local start = os.clock()
local K = searchPrimes(2, N)
local e = os.clock()
io.write(string.format("time: %.8f seconds, primes: %f\n", e - start, K))
start = os.clock()
K = primes(N)
local e = os.clock()
io.write(string.format("time: %.8f seconds, primes: %f\n", e - start, K))
start = os.clock()
K = primes2(N)
local e = os.clock()
io.write(string.format("time: %.8f seconds, primes: %f\n", e - start, K))
function searchPrimes(reg from,reg to){
reg (dummy,primes,n,i,j,isPrime)=(0,0,0,0,0,0);
from=+from;
to=+to;
for(n=from;n<=to;++n){
i=((n%2)==0)?2:3;
j=n**0.5;
isPrime=1;
while(i<=j){
if((n%i)==0){
isPrime=0;
break;
}
i+=2;
}
primes+=isPrime;
}
return primes;
}
function isprime(reg n){
n = +n;
for(reg i = 2; i < n; i++){
if((n % i) == 0){
return false;
}
}
return true;
}
function primes(reg n){
reg count = 0;
n = +n;
for(reg i = 2; i <= n; i++){
if(isprime(i)){
count++;
}
}
return count;
}
function primes2(reg n){
n = +n;
reg count = 0, isPrime = 0, i = 0, j = 0;
for(i = 2; i <= n; i++){
isPrime = 1;
for(j = 2; j < i; j++){
if((i % j) == 0){
isPrime = 0;
break;
}
}
count += isPrime;
}
return count;
}
reg N = 200000, ta = 0, tb = 0, p = 0;
ta=DateTime.now();
p = searchPrimes(2, N);
tb=DateTime.now();
puts("time: ", Math.round(DateTime.milliseconds(tb-ta))*0.001, " seconds, primes: ", p);
ta=DateTime.now();
p = primes(N);
tb=DateTime.now();
puts("time: ", Math.round(DateTime.milliseconds(tb-ta))*0.001, " seconds, primes: ", p);
ta=DateTime.now();
p = primes2(N);
tb=DateTime.now();
puts("time: ", Math.round(DateTime.milliseconds(tb-ta))*0.001, " seconds, primes: ", p);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment