-1

I am trying to calculate the factorial of very large numbers using threads but the threadless function is calculating faster.How can i use parallel computing with threads---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

public class Faktoriyel implements Runnable{

private Sayi sayi;
public Sayi faktoriyelSonuc;
public Faktoriyel(Sayi sayi){
    this.sayi = sayi;
}

@Override
public void run() {
BigInteger fact = new BigInteger("1");
for (int i = 1 ;i <= sayi.GetSayi().longValue() ; i++) {
    fact = fact.multiply(new BigInteger(i + ""));
    }     
faktoriyelSonuc = new Sayi(fact.toString());
System.out.println(faktoriyelSonuc.GetSayi());
}
}

These are main ---

public class Project1{

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    long baslangicSeri = System.nanoTime();
    System.out.println(SeriFaktoriyel(new Sayi("200000")));
    long bitisSeri = System.nanoTime();
    double SerigecenSure = (double)(bitisSeri-baslangicSeri)/1000000000;
    System.out.println("Seri Hesaplama : "+SerigecenSure+" saniye");

    long baslangicParalel = System.nanoTime();
    ExecutorService havuz = Executors.newFixedThreadPool(10);
    havuz.execute(new Faktoriyel(new Sayi("200000")));
    havuz.shutdown();
    while(!havuz.isTerminated()){ }
    long bitisParalel = System.nanoTime();
    double gecenSure = (double)(bitisParalel-baslangicParalel)/1000000000;
    System.out.println("Paralel hesaplama : "+gecenSure+" saniye");     
} 

public static String SeriFaktoriyel(Sayi sayi){
     BigInteger fact = new BigInteger("1");
for (int i = 1; i <= sayi.GetSayi().longValue() ; i++) {
    fact = fact.multiply(new BigInteger(i + ""));
    }
   return fact.toString();
}
}
yasiryildirtan
  • 19
  • 1
  • 1
  • 5

1 Answers1

1

There are a two things that I can point out that damage the performance of your threaded version:

  • System.out.println() is a system call which has a significant overhead, and it is applied only in the threaded version.
  • You are using a thread-pool of size 10 , unless you have 10 cores on your computer, it means that your program suffers from redundant context switches. (You will get better performance with a thread pool in the size of your actual amount of pc cores)

If this is Chinese to you I would recommend reading about context switches :)

Idan Beker
  • 353
  • 2
  • 9