criei um algorithmo para gerar um milhão de numeros primos, em C ele roda em 5 segundos, em java ele leva 33 segundos. Ambos no meu macbook e ambos utilizão a mesma logica…
gostaria de saber como aumentar a performance do algoritimo para rodar sobre a maquina virtual, estou postando o mesmo tanto em C quanto em Java, e tambem o benchmark do tempo de compilação e execução de ambos…
Em C
/*
* Primes.c
*
*
* Created by Marcos Sartori on 28/10/2009.
* Copyright 2009 Marcos Sartori Computer Systems. All rights reserved.
*
*/
#include <stdio.h>
#include <math.h>
#define TRUE -1
#define FALSE 0
int isPrime(unsigned int aNumber);
int main (int argc, char* argv)
{
unsigned register int i, z;
i = 0; z = 0;
while (z<1000000){
if (isPrime(i)){
printf("%d\n", i);
z++;
}
i++;
}
return 0;
}
int isPrime(unsigned int aNumber)
{
unsigned register int i, z, j;
if (aNumber<=1) return FALSE;
if ((!(aNumber&1))&&(aNumber!=2)) return FALSE;
z=aNumber>11?11:aNumber-1; goto loop;
sqrt:
z=sqrt(aNumber); j = TRUE;
loop:
for (i=3; i<=z; i+=2)
if (!(aNumber%i)) return FALSE;
if(!j) goto sqrt; //Just to be sure, check it again, but this time check all posible divisors untill its square root
return TRUE;
}
Em Java
/**
* Write a description of class Prime here.
*
* @author Marcos Sartori
* @version 20091028
*/
public class Prime
{
public static void main(String[] argv)
{
int i, z;
i = 0; z = 0;
while (z<1000000){
if(isPrime(i)){
System.out.println(i);
z++;
}
i++;
}
}
public static boolean isPrime(int aNumber)
{
if(aNumber<=1) return false;
if(((aNumber&1)==0)&&(aNumber!=2)) return false;
int z = aNumber>11?11:aNumber-1;
for(int i = 3 ; i<=z ; i+=2)
if((aNumber%i)==0) return false;
z = (int)Math.sqrt(aNumber);
for(int i = 3 ; i<=z ; i+=2)
if((aNumber%i)==0) return false;
return true;
}
}
Benchmarks (Tempos de Execução)
Macbook-de-Marcos-Sartori:Developer marcos$ time gcc -o Prime Prime.c
real 0m0.076s
user 0m0.033s
sys 0m0.024s
Macbook-de-Marcos-Sartori:Developer marcos$ time javac Prime.java
real 0m1.036s
user 0m1.459s
sys 0m0.161s
Macbook-de-Marcos-Sartori:Developer marcos$ time ./Prime > primes.txt
real 0m5.160s
user 0m4.842s
sys 0m0.025s
Macbook-de-Marcos-Sartori:Developer marcos$ time java Prime > primes.txt
real 0m33.792s
user 0m23.244s
sys 0m10.115s
Macbook-de-Marcos-Sartori:Developer marcos$
se alguem tiver alguma ideia, por favor não hesite, e me de uma mão…
Obrigado…