120 likes | 201 Views
Computer Science 320. A First Program in Parallel Java. A Simple Program. Test several numbers for primes First develop a sequential version Then develop a parallel version Compare the running times. A Test for Primality. public static boolean isPrime (long x){
E N D
Computer Science 320 A First Program in Parallel Java
A Simple Program • Test several numbers for primes • First develop a sequential version • Then develop a parallel version • Compare the running times
A Test for Primality public static booleanisPrime(long x){ if (x % 2 == 0) return false; long p = 3; long psqr = p * p; while (psqr <= x){ if (x % p == 0) return false; p += 2; psqr= p * p; } return true; } Divide x by 2 and by every odd number from 3 up to the square root of x. If remainder is 0, not prime!
Testing n Numbers Sequentially static int n; static long[] x; public static void main(String[] args) throws Exception{ n = args.length; x = new long[n]; for (inti = 0; i < n; ++i) x[i] = Long.parseLong(args[i]); for (inti = 0; i < n; ++i) isPrime(x[i]); } Processes the command line arguments as inputs
Add Some Timing static int n; static long[] x; static long t1, t2[], t3[]; public static void main(String[] args) throws Exception{ t1 = System.currentTimeMillis(); n = args.length; x = new long[n]; for (inti = 0; i < n; ++i) x[i] = Long.parseLong(args[i]); t2 = new long[n]; t3 = new long[n]; for (inti = 0; i < n; ++i){ t2[i] = System.currentTimeMillis(); isPrime(x[i]); t3[i] = System.currentTimeMillis(); } for (inti = 0; i < n; ++i){ System.out.println("i = " + i + " call start = " + (t2[i] - t1) + " msec"); System.out.println("i = " + i + " call finish = " + (t3[i] - t1) + " msec"); } }
Testing n Numbers in Parallel, SMP import edu.rit.pj.ParallelTeam; static int n; static long[] x; public static void main(String[] args) throws Exception{ n = args.length; x = new long[n]; for (inti = 0; i < n; ++i) x[i] = Long.parseLong(args[i]); new ParallelTeam(n) . . . } The parallel team will contain as many threads as there are inputs.
Specify Code to Run in Each Thread import edu.rit.pj.ParallelRegion; import edu.rit.pj.ParallelTeam; new ParallelTeam(n).execute(new ParallelRegion(){ public void run(){ inti = getThreadIndex(); isPrime(x[i]); } }); A parallel region contains the code that runs in each thread. Each thread executes the same run method, but with a different input value.
Add the Timing new ParallelTeam(n).execute(new ParallelRegion(){ public void run(){ inti = getThreadIndex(); t2[i] = System.currentTimeMillis(); isPrime(x[i]); t3[i] = System.currentTimeMillis(); } });
A New View of Repetition • Logically, a loop repeats a sequence of instructions • On a sequential machine, the sequence is repeated • On a parallel computer, the sequence can be copied and distributed to multiple processors