I am making a java program which compares how much time it takes to calculate the total of prime numbers there are between two given numbers. I have to calculate how much it takes sequentially and also with threads.
For example, I have to check how much it takes to calculate sequentially:
PrimeNumbers pn = new PrimeNumbers (1,1000); And compare it with how much it takes to calculate the same thing but dividing it in several threads:
PrimeThread p1 = new PrimeThread (1, 200); PrimeThread p2 = new PrimeThread (201, 400); PrimeThread p3 = new PrimeThread (401, 600); PrimeThread p4 = new PrimeThread (601, 800); PrimeThread p5 = new PrimeThread (801, 1000); I have to use System.currentTimeMillis() to calculate the time. Threads should be able to calculate the same thing faster, but it is actually slower. So far I have this code:
PrimeNumbers pn = new PrimeNumbers(1,1000); long startTimeSeq = System.currentTimeMillis(); int totalNumbersSeq = pn.calculatePrimeNumbers(); long finishTimeSeq = System.currentTimeMillis(); float totalTimeSeq = finishTimeSeq - startTimeSeq; PrimeThread p1 = new PrimeThread (1, 200); PrimeThread p2 = new PrimeThread (201, 400); PrimeThread p3 = new PrimeThread (401, 600); PrimeThread p4 = new PrimeThread (601, 800); PrimeThread p5 = new PrimeThread (801, 1000); long startTimeThread = System.currentTimeMillis(); p1.start(); p2.start(); p3.start(); p4.start(); p5.start(); try { p1.join(); p2.join(); p3.join(); p4.join();p5.join(); } catch (InterruptedException e) { e.printStackTrace(); } long finishTimeThread = System.currentTimeMillis(); float totalTimeThread = finishTimeThread - startTimeThread; int totalNumbersThread = p1.getNumPrimers() + p2.getNumPrimers() + p3.getNumPrimers() + p4.getNumPrimers() + p5.getNumPrimers(); System.out.println("Total prime numbers sequentially: " + numPrimers); System.out.println("Total time: " + totalTimeSeq); System.out.println("Total prime numbers with threads: " + resultatFinal); System.out.println("Total time: " + totalTimeThread); The outcome of the prints is:
Total prime numbers sequentially: 169 Total time: 1.0 Total prime numbers with threads: 169 Total time: 3.0 I'm sorry if I this is messy, it is my first time posting here and I'm new to programing. Thank you so much.