STIW3054-A172 / Main-Issues

1 stars 1 forks source link

Exercise_03 #4

Closed zhamri closed 6 years ago

zhamri commented 6 years ago

Write a program to find a maximum number in a list of 1,000,000 random numbers using sequential program and concurrent program. Then compare the execution times for both approaches. The results should be displayed in 'second'.

Example of output:

Sequential Program = 11.000012 seconds
Concurrent Program = 5.000025 seconds

diyanazaidi commented 6 years ago

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.mycompany.ex03;

import java.util.Random;

/**
 *
 * @author User
 */
public class main {

    public static void main(String[] args) {

        sequential s = new sequential();
        s.count();

        ThreadThread ts = new ThreadThread();
        ts.test();

    }

    public static class sequential {

        public void count() {

            long startTime = System.nanoTime();
            long total = 0;

            Random aGenerator = new Random();

            int randomArray[] = new int[1000000];
            int countArray[] = new int[1000000];

            //generate the numbers and store into an array
            int j;
            for (int i = 1; i < 1000000; ++i) {
                j = i;
                randomArray[i] = aGenerator.nextInt(1000000);

                //displaying numbers
                //System.out.println("Number " + j + " = " + randomArray[i]);
            }

            int max = randomArray[0];
            for (int i = 1; i < randomArray.length; i++) {

                if (randomArray[i] > max) {
                    max = randomArray[i];
                }
                //System.out.println("Max number is "+ max);
            }

            long stopTime = System.nanoTime();
            long elapsedTime = stopTime - startTime;
            double seconds = (double) elapsedTime / 1000000000.0;
            System.out.printf("\nSequential program = %.9f seconds", seconds);
        }
    }

    public static class ThreadThread extends Thread {

        @Override
        public void run() {
            Random aGenerator = new Random();

            int randomArray[] = new int[1000000];
            int countArray[] = new int[1000000];

            //generate the numbers and store into an array
            int j;
            for (int i = 1; i < 1000000; ++i) {
                j = i;
                randomArray[i] = aGenerator.nextInt(1000000);

                //displaying numbers
                //System.out.println("Number " + j + " = " + randomArray[i]);
            }

            int max = randomArray[0];
            for (int i = 1; i < randomArray.length; i++) {

                if (randomArray[i] > max) {
                    max = randomArray[i];
                }
                //System.out.println("Max number is "+ max);
            }
        }

        public void test() {
            long startTime = System.nanoTime();
            long total = 0;

            ThreadThread te = new ThreadThread();
            Thread thread1 = new Thread(te);
            Thread thread2 = new Thread(te);

            thread1.start();
            thread2.start();

            long stopTime = System.nanoTime();
            long elapsedTime = stopTime - startTime;
            double seconds = (double) elapsedTime / 1000000000.0;

            System.out.printf("\nConcurrent program = %.9f seconds", seconds);
        }

    }

}

output

image

kzkit commented 6 years ago

Sequence program

package randomworks;

import java.util.ArrayList;
import java.util.Random;

public class sequence {
    private int intToFind;
    private int startIndex;
    private int endIndex;
    private int[] arrayToSearchIn;

    public static void main(String[] args) {
        long startTime = System.nanoTime();
        int pick=0;
        ArrayList al = new ArrayList(); 
        Random rand = new Random();
        int count;
        int index = 0;
        for (int j = 0; j<1000000; j++)
        {
        pick = rand.nextInt(1000000);
        al.add(pick);

        }
        int max = (int) al.get(0);
        for(int i = 0; i < al.size(); i++) {
        int number = (int) al.get(i);
        if(number > max) max = number;
        }
        System.out.println("Max is : " +max);
        long stopTime = System.nanoTime();
        long elapsedTime = stopTime - startTime;
        double seconds = (double) elapsedTime / 1000000000.0;
         System.out.printf("\nProgram ended at %.9f seconds", seconds);
        }
    }

Concurrent :

package randomworks;

import java.util.Random;

public class concurrent {

    public static void main(String[] args) {
        long startTime = System.nanoTime();
        int[] numbers = new int[100000];
        Random rnd = new Random();
        for (int index = 0; index < numbers.length; index++) {
            numbers[index] = rnd.nextInt();
        }

        Thread[] threads = new Thread[10];
        Worker[] workers = new Worker[10];

        int range = numbers.length / 10;
        for (int index = 0; index < 10; index++) {
            int startAt = index * range;
            int endAt = startAt + range;
            workers[index] = new Worker(startAt, endAt, numbers);
        }

        for (int index = 0; index < 10; index++) {
            threads[index] = new Thread(workers[index]);
            threads[index].start();
        }

        boolean isProcessing = false;
        do {
            isProcessing = false;
            for (Thread t : threads) {
                if (t.isAlive()) {
                    isProcessing = true;
                    break;
                }
            }
        } while (isProcessing);
         int finalMax = workers[0].getMax();
        for (Worker worker : workers) {

          for (int x = 1; x < workers.length; x++) {
         if(finalMax < workers[x].getMax())      
           finalMax = workers[x].getMax();        
        }

        }
         System.out.println("Final Max " + finalMax );
         long stopTime = System.nanoTime();
        long elapsedTime = stopTime - startTime;
        double seconds = (double) elapsedTime / 1000000000.0;
        System.out.printf("\nProgram ended at %.9f seconds", seconds);
    }

    public static class Worker implements Runnable {

        private int startAt;
        private int endAt;
        private int numbers[];

        private int max = Integer.MIN_VALUE;

        public Worker(int startAt, int endAt, int[] numbers) {
            this.startAt = startAt;
            this.endAt = endAt;
            this.numbers = numbers;
        }

        @Override
        public void run() {
            for (int index = startAt; index < endAt; index++) {
                max = Math.max(numbers[index], max);
            }
        }

        public int getMax() {
            return max;
        }

    }

}

Sequence result :

issue3

Concurrent result :

issue3-1

nurulbasitah commented 6 years ago

Sequential program

package issue04_exercise;

public class sequential{

    public static void randomMaxnum() throws InterruptedException{
    int numbers[] = new int[1000000];       
    for(int i = 0; i < 1000000; i++) {
      numbers[i] = (int)(Math.random()*1000000 + 1);
      //System.out.println("Numbers Generated: " + numbers[i]); 
    }//end for loop

    int max  = numbers[0];
    for (int i= 0; i<numbers.length ; i++){
        if (numbers[i]>max){
            max = numbers[i];
            //System.out.println(max);
        }
}

    }
        public static void main(String [] args) throws InterruptedException{
        long startTime = System.nanoTime();
        randomMaxnum();
        long endTime = System.nanoTime();
        long output = endTime - startTime;
        double result = (double) output/1000000000.0;
        System.out.printf("\n Sequential program = %.9f seconds",result );
    }
}

Concurrent program

package issue04_exercise;

public class Concurrent{

    public static class number extends Thread{
        public void run(){
            int numbers[] = new int[1000000];       
    for(int i = 0; i < 1000000; i++) {
      numbers[i] = (int)(Math.random()*1000000 + 1);
      //System.out.println("Numbers Generated: " + numbers[i]); 
    }//end for loop

    int max  = numbers[0];
    for (int i= 0; i<numbers.length ; i++){
        if (numbers[i]>max){
            max = numbers[i];
            //System.out.println(max);
        }
    }

   }    
}
         public static void main(String [] args){
        long startTime = System.nanoTime();
        number cuba = new number();
        Thread thread1 = new Thread(cuba);
        Thread thread2 = new Thread(cuba);

        thread1.start();
        thread2.start();
        long endTime = System.nanoTime();
        long output = endTime - startTime;
        double result = (double) output/1000000000.0;
        System.out.printf("\n Concurrent program = %.9f seconds",result );

    }    
}

Sequential and Concurrent output:

issue_3 issue_3_1

AsadRazali commented 6 years ago

import java.util.Random; import java.util.concurrent.TimeUnit;

class one implements Runnable { public void run() { int collect[] = new int[1000000]; for (int i = 0; i < 1000000; i++) {

        Random rn = new Random();
        collect[i] = rn.nextInt();
    }
    int max = collect[0];
        for (int i=1; i<collect.length; i++) {

            if (collect[i] > max) {
                max =  collect[i];
            }

        }
}

} class Exercise3 { public static void main(String arg[]) { Exercise3 num = new Exercise3(); num.seq(); num.con();

    }
    public void con()
    {
        int i =0;
    one ob = new one();
    Thread th;
    double t1=System.nanoTime();
    try
    {   
                for(i=0; i<1000; i++)
                {
                th=new Thread(ob);
                th.start();
                }

                double t2=System.nanoTime();
                System.out.println("Concurrent program =" + ((t2-t1)/1000000000 ) + " second");
            }
    catch(OutOfMemoryError e)
    {
    System.out.println("Not enought memory");
    }
    }

    public void seq()
    {

      double t1=System.nanoTime();
        int collect[] = new int[1000000];
        for (int i = 0; i < 1000000; i++) {

        Random rn = new Random();
        collect[i] = rn.nextInt();
    }
    int max = collect[0];
        for (int i=1; i<collect.length; i++) {

            if (collect[i] > max) {
                max =  collect[i];
            }

        }

    double t2=System.nanoTime();
    System.out.println("Sequential program = " + ((t2-t1)/1000000000 ) + " second");
    }

}

result

Reference

  1. https://www.youtube.com/watch?v=tDp19pXPxQY
  2. https://stackoverflow.com/questions/924208/how-to-convert-nanoseconds-to-seconds-using-the-timeunit-enum
adamrustam commented 6 years ago

Sequential :

import java.util.Collections;
import java.util.Random;

public class Sequential {
    public static void main(String[] args) {

         //start
        long lStartTime = System.nanoTime();

        int i;
        Random r = new Random();
        int largest = Integer.MIN_VALUE;

        // generate a uniformly distributed int random numbers
        int[] integers = new int[1000000];
        for ( i = 0; i < 1000000 ; i++) {
            integers[i] = r.nextInt(1000000);

        //System.out.println(integers[i]);

        }

         for( i =0;i<integers.length;i++) {

             if(integers[i] > largest) {

                 largest = integers[i];

                      //System.out.println("Largest number in array is : " +largest);

                }

        }

        //end
        long lEndTime = System.nanoTime();

        //time elapsed
        long output = lEndTime - lStartTime;

        System.out.println("Elapsed time in seconds: " + output / 1000000000.0);

    }
}

Concurrent :

import java.util.Random;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author adamrustam
 */
public class Concurrent {

    public static void main(String[] args) {

         //start
        long lStartTime = System.nanoTime();
        gg trd = new gg ();
        Thread t1 = new Thread(trd);
        Thread t2 = new Thread(trd);

        long lEndTime = System.nanoTime();

        //time elapsed
        long output = lEndTime - lStartTime;

        System.out.println("Elapsed time in seconds: " + output / 1000000000.0);

    }

    public static class gg extends Thread{

    public void calculation () {

        int i;
        Random r = new Random();
        int largest = Integer.MIN_VALUE;

        // generate a uniformly distributed int random numbers
        int[] integers = new int[1000000];
        for ( i = 0; i < 1000000 ; i++) {
            integers[i] = r.nextInt(1000000);

        //System.out.println(integers[i]);

        }

         for( i =0;i<integers.length;i++) {

             if(integers[i] > largest) {

                 largest = integers[i];

                      //System.out.println("Largest number in array is : " +largest);

                }

        }

    }

    }

}

Output Sequential

screen shot 2018-03-21 at 2 34 07 am

Output Concurrent

screen shot 2018-03-21 at 2 33 53 am

References

https://www.java-examples.com/find-largest-and-smallest-number-array-example https://www.mkyong.com/java/how-do-calculate-elapsed-execute-time-in-java/

AdlanShahjehan commented 6 years ago

Sequential.java

import exercise3.Concurrent.Concurrents;
import java.util.Random;

public class Sequential {

    public static void main(String[] args) {

        sequential S = new sequential();
        S.Sequential();

        Concurrents C = new Concurrents();
        C.Concurrent();
    }

    public static class sequential {

        public void Sequential() {
            long startTime = System.nanoTime();
            int Array[] = new int[1000000];
            Random aGenerator = new Random();

            for (int i = 1; i < 1000000; ++i) {
                Array[i] = aGenerator.nextInt(1000000);
            }

            int max = Array[1];
            for (int i = 1; i < Array.length; i++) {
                if (Array[i] > max) {
                    max = Array[i];
                }
            }

            long stopTime = System.nanoTime();
            long elapsedTime = stopTime - startTime;
            double seconds = (double) elapsedTime / 1000000000.0;
            System.out.printf("\nSequential program = %.9f seconds", seconds);
        }
    }
}

Concurrent.java

import java.util.Random;

public class Concurrent {

     public static class Concurrents extends Thread {

       public void Concurrent() {

            Random aGenerator = new Random();

            int Array[] = new int[1000000];

            for (int i = 1; i < 1000000; ++i) {
               int j = i;
                Array[i] = aGenerator.nextInt(1000000);
            }

            int max = Array[1];
            for (int i = 1; i < Array.length; i++) {

                if (Array[i] > max) {
                    max = Array[i];
                }
            }

            long startTime = System.nanoTime();
            Concurrents t = new Concurrents();
            Thread t1 = new Thread(t);
            Thread t2 = new Thread(t);
            t1.start();
            t2.start();

            long stopTime = System.nanoTime();
            long elapsedTime = stopTime - startTime;
            double seconds = (double) elapsedTime / 1000000000.0;
            System.out.printf("\nConcurrent program = %.9f seconds", seconds);
            System.out.println();
        }
    }   
}

Output

capture

ghost commented 6 years ago
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import java.util.Random;

/**
 *
 * @author RASYID
 */
public class Question2 {

    //SEQUENTIAL CLASS

    public static class sequential_part {

        public void count() {
            long timeStart = System.nanoTime();

            Random ran = new Random();
            int arrayRandom[] = new int[1000000];

            for (int i = 0; i < 1000000; i++) {
                arrayRandom[i] = ran.nextInt(1000000);
            }

            int max = arrayRandom[0];
            for (int i = 0; i < arrayRandom.length; i++) {
               if(arrayRandom[i]>max){
                   max = arrayRandom[i];
               } 
            }

            long endTime = System.nanoTime();
            long timeLength = endTime - timeStart;
            double sec = (double) timeLength/1000000000.0;
            System.out.printf("\nSequential program = %.9f seconds", sec);

        }
    }

    //COCURRENT CLASS

    public static class Concurrent_Part extends Thread{
        public void count(){

            Random ran = new Random();

            int []nilai = new int[1000000];

            for(int i=0; i<1000000; i++){
                nilai[i] = ran.nextInt(1000000);
            }

            int max = nilai[0];
            for (int i = 0; i < nilai.length; i++) {
               if(nilai[i]>max){
                   max = nilai[i];
               } 
            }

            Concurrent_Part t = new Concurrent_Part();
            Thread t1 = new Thread(t);
            Thread t2 = new Thread(t);

            t1.start();
            t2.start();

            long startTime = System.nanoTime();
            long endTime = System.nanoTime();
            long timeLength = endTime - startTime;
            double sec = (double) timeLength/1000000000.0;
            System.out.printf("\nSequential program = %.9f seconds", sec);

        }
    }

    public static void main(String[] args) {

        sequential_part a = new sequential_part();
        a.count();

        Concurrent_Part b = new Concurrent_Part();
        b.count();
    }

}

Results :

screen shot 03-21-18 at 01 23 pm

Nurzyra commented 6 years ago
package sequence;

import java.util.ArrayList;
import java.util.Random;

public class Sequence {

    private int intToFind;
    private int startIndex;
    private int endIndex;
    private int[] arrayToSearchIn;

    public static void main(String[] args) {
        long startTime = System.nanoTime();
        int pick=0;
        ArrayList array = new ArrayList(); 
        Random rand = new Random();
        int count;
        int index = 0;
        for (int j = 0; j<1000000; j++)
        {
        pick = rand.nextInt(1000000);
        array.add(pick);

        }
        int max = (int) array.get(0);
        for(int i = 0; i < array.size(); i++) {
        int number = (int) array.get(i);
        if(number > max) max = number;
        }
        System.out.println("Max is : " +max);
        long stopTime = System.nanoTime();
        long elapsedTime = stopTime - startTime;
        double seconds = (double) elapsedTime / 1000000000.0;
        System.out.printf("\n End at %.9f seconds", seconds);
        }
    }

1

package concurrent; 

public class Concurrent{

    public static class number extends Thread{
        public void run(){
            int numbers[] = new int[1000000];       
    for(int i = 0; i < 1000000; i++) {
      numbers[i] = (int)(Math.random()*1000000 + 1); 
    }

    int max  = numbers[0];
    for (int i= 0; i<numbers.length ; i++){
        if (numbers[i]>max){
            max = numbers[i];
        }
    }

   }    
}
        public static void main(String [] args){
        long startTime = System.nanoTime();
        number num = new number();
        Thread thread1 = new Thread(num);
        Thread thread2 = new Thread(num);

        thread1.start();
        thread2.start();
        long endTime = System.nanoTime();
        long output = endTime - startTime;
        double result = (double) output/1000000000.0;
        System.out.printf("\n Concurrent program = %.9f seconds",result );

    }    
}

2

saufisyafiq commented 6 years ago

Main.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex3;

/**
 *
 * @author Saufi
 */
public class Ex3 {

    /**
     * @param args the command line arguments
     * @throws java.lang.InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {

        int n[]=new int [1000000];

        Sequential.maxRandomNum(n);
        Concurrent.number.con(n);

    }

    }

Sequential.java

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex3;

/**
 *
 * @author Saufi
 */
public class Sequential {

            public static void maxRandomNum(int[] num ) throws InterruptedException{
    int[] n= num;     

    for(int i = 0; i < 1000000; i++) {
      n[i] = (int)(Math.random()*1000000 + 1);
    }

    int ArrayofMax  = n[0];
    for (int i= 0; i<n.length ; i++){
        if (n[i]>ArrayofMax){
            ArrayofMax = n[i];

        }
}

        long start = System.nanoTime();
        long end = System.nanoTime();
        long output = end - start;
        double result = (double) output/1000000000.0;
        System.out.printf("\nSequential program = %.9f seconds ",result );
    }

}

Concurrent.java


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package ex3;

/**
 *
 * @author Saufi
 */
public class Concurrent {

    public static  class number extends Thread{
        public static void con(int[] num){
            int[] n = num;

    for(int i = 0; i < 1000000; i++) {
      n[i] = (int)(Math.random()*1000000 + 1);
      //System.out.println("Numbers Generated: " + numbers[i]); 
    }//end for loop

    int ArrayofMax  = n[0];
    for (int i= 0; i<n.length ; i++){
        if (n[i]>ArrayofMax){
            ArrayofMax = n[i];
            //System.out.println(max);
        }
    }

   long start = System.nanoTime();
        number number = new number();
        Thread thread1 = new Thread(number);
        Thread thread2 = new Thread(number);

        thread1.start();
        thread2.start();
        long end;
         end = System.nanoTime();
        long output = end - start;
        double result = (double) output/1000000000.0;
        System.out.printf("\nConcurrent program = %.9f seconds \n",result );

        }    
}

}

)

scex3