File: PrimeCountFunctionHyb.java

package info (click to toggle)
libpj-java 0.0~20150107%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye
  • size: 13,396 kB
  • sloc: java: 99,543; ansic: 987; sh: 153; xml: 26; makefile: 10; sed: 4
file content (288 lines) | stat: -rw-r--r-- 9,786 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
//******************************************************************************
//
// File:    PrimeCountFunctionHyb.java
// Package: edu.rit.hyb.prime
// Unit:    Class edu.rit.hyb.prime.PrimeCountFunctionHyb
//
// This Java source file is copyright (C) 2012 by Alan Kaminsky. All rights
// reserved. For further information, contact the author, Alan Kaminsky, at
// ark@cs.rit.edu.
//
// This Java source file is part of the Parallel Java Library ("PJ"). PJ is free
// software; you can redistribute it and/or modify it under the terms of the GNU
// General Public License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// PJ is distributed in the hope that it will be useful, but WITHOUT ANY
// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
// A PARTICULAR PURPOSE. See the GNU General Public License for more details.
//
// Linking this library statically or dynamically with other modules is making a
// combined work based on this library. Thus, the terms and conditions of the
// GNU General Public License cover the whole combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent modules, and
// to copy and distribute the resulting executable under terms of your choice,
// provided that you also meet, for each linked independent module, the terms
// and conditions of the license of that module. An independent module is a
// module which is not derived from or based on this library. If you modify this
// library, you may extend this exception to your version of the library, but
// you are not obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
//
// A copy of the GNU General Public License is provided in the file gpl.txt. You
// may also obtain a copy of the GNU General Public License on the World Wide
// Web at http://www.gnu.org/licenses/gpl.html.
//
//******************************************************************************

package edu.rit.hyb.prime;

import edu.rit.mp.LongBuf;

import edu.rit.mp.buf.LongItemBuf;

import edu.rit.pj.Comm;
import edu.rit.pj.LongForLoop;
import edu.rit.pj.LongSchedule;
import edu.rit.pj.ParallelRegion;
import edu.rit.pj.ParallelTeam;
import edu.rit.pj.WorkerLongForLoop;
import edu.rit.pj.WorkerRegion;
import edu.rit.pj.WorkerTeam;

import edu.rit.pj.reduction.LongOp;
import edu.rit.pj.reduction.SharedLong;

import java.io.File;

/**
 * Class PrimeCountFunctionHyb is a hybrid parallel program that calculates the
 * prime counting function &pi;(<I>x</I>). &pi;(<I>x</I>) is the number of
 * primes less than or equal to <I>x</I>. The program uses a list of 32-bit
 * primes stored in a file. The prime file must be generated by the {@linkplain
 * Prime32File} program. To find the primes, the program calculates a series of
 * sieves. Each sieve consists of one million numbers.
 * <P>
 * The program runs with one process per node and multiple threads per process.
 * The program uses the master-worker pattern for load balancing. Each process
 * in the program is an independent worker process. Each worker process
 * calculates a series of groups of sieves, as assigned by the master thread.
 * Within each group of sieves, the threads of the worker process calculate the
 * individual sieves in parallel.
 * <P>
 * The groups of sieves are determined by the <TT>pj.schedule</TT> property
 * specified on the command line; the default is to divide the sieves evenly
 * among the worker processes (i.e. no load balancing). For further information
 * about the <TT>pj.schedule</TT> property, see class {@linkplain
 * edu.rit.pj.PJProperties PJProperties}.
 * <P>
 * Within each group of sieves, the individual sieves are partitioned among the
 * threads of the worker process using the parallel loop schedule specified by
 * the last command line argument. If this argument is missing, the default is
 * to divide the individual sieves evenly among the threads (i.e. no load
 * balancing). For further information, see the <TT>parse()</TT> method in class
 * {@linkplain edu.rit.pj.IntegerSchedule IntegerSchedule}.
 * <P>
 * Usage: java -Dpj.np=<I>Kp</I> -Dpj.nt=<I>Kt</I> [
 * -Dpj.schedule=<I>procschedule</I> ] edu.rit.hyb.prime.PrimeCountFunctionHyb
 * <I>x</I> <I>primefile</I> [ <I>thrschedule</I> ]
 * <BR><I>Kp</I> = Number of parallel processes
 * <BR><I>Kt</I> = Number of parallel threads per process
 * <BR><I>procschedule</I> = Load balancing schedule for processes
 * <BR><I>x</I> = Argument of prime counting function, 0 &lt;= <I>x</I> &lt;=
 * 2<SUP>63</SUP>-1
 * <BR><I>primefile</I> = Prime file name
 * <BR><I>thrschedule</I> = Load balancing schedule for threads
 * <P>
 * The computation is performed in parallel in multiple processors. The program
 * measures the total running time.
 *
 * @author  Alan Kaminsky
 * @version 19-Mar-2012
 */
public class PrimeCountFunctionHyb
	{

// Prevent construction.

	private PrimeCountFunctionHyb()
		{
		}

// Shared global variables.

	// Sieve in one-million-number chunks.
	static final int CHUNK = 1000000;

	// World communicator.
	static Comm world;
	static int rank;

	// Command line arguments.
	static long x;
	static File primeFile;
	static LongSchedule thrSchedule;

	// Parallel team.
	static ParallelTeam team;

	// Per-thread sieves.
	static Sieve[] sieves;

	// List of 32-bit primes.
	static Prime32List primeList;

	// Per-process prime counter.
	static SharedLong primeCount = new SharedLong (0);

// Main program.

	/**
	 * Main program.
	 */
	public static void main
		(String[] args)
		throws Exception
		{
		// Start timing.
		long t1 = System.currentTimeMillis();

		// World communicator.
		Comm.init (args);
		world = Comm.world();
		rank = world.rank();

		// Parse command line arguments.
		if (args.length < 2 || args.length > 3) usage();
		x = Long.parseLong (args[0]);
		if (x < 0) usage();
		primeFile = new File (args[1]);
		thrSchedule =
			args.length == 3 ?
				LongSchedule.parse (args[2]) :
				LongSchedule.fixed();

		// Set up parallel team and per-thread sieves.
		team = new ParallelTeam();
		sieves = new Sieve [team.getThreadCount()];
		for (int i = 0; i < sieves.length; ++ i)
			{
			sieves[i] = new Sieve (0, CHUNK);
			}

		// Set up list of 32-bit primes.
		primeList = new Prime32List (primeFile);

		// Compute sieves in parallel using a two-level schedule for load
		// balancing. First-level schedule controlled by -Dpj.schedule.
		new WorkerTeam().execute (new WorkerRegion()
			{
			public void run() throws Exception
				{
				// Determine number of sieves to calculate.
				long ns = (x + CHUNK - 1)/CHUNK;
				execute (0, ns - 1, new WorkerLongForLoop()
					{
					public void run (final long lb, final long ub)
						throws Exception
						{
						team.execute (new ParallelRegion()
							{
							public void run() throws Exception
								{
								execute (lb, ub, new LongForLoop()
									{
									// Per-thread variables plus extra padding.
									Sieve thrSieve;
									long thrPrimeCount;
									long p0, p1, p2, p3, p4, p5, p6, p7;
									long p8, p9, pa, pb, pc, pd, pe, pf;

									// Second-level schedule controlled by last
									// command line argument.
									public LongSchedule schedule()
										{
										return thrSchedule;
										}

									// Initialize per-thread variables.
									public void start()
										{
										thrSieve = sieves[getThreadIndex()];
										thrPrimeCount = 0;
										}

									// Calculate all sieves.
									public void run (long first, long last)
										throws Exception
										{
										for (long lb = first; lb <= last; ++ lb)
											{
											// Get an iterator for the odd
											// primes.
											LongIterator iter =
												primeList.iterator();

											// Calculate the sieve.
											thrSieve.lb (lb*CHUNK);
											thrSieve.initialize();
											thrSieve.sieveOut (iter);

											// Count primes <= x left in the
											// sieve.
											iter = thrSieve.iterator();
											long p;
											while ((p = iter.next()) != 0 &&
													p <= x)
												{
												++ thrPrimeCount;
												}
											}
										}

									// Reduce per-thread prime count into
									// per-process prime count.
									public void finish()
										{
										primeCount.addAndGet (thrPrimeCount);
										}
									});
								}
							});
						}
					});
				}
			});

		// Reduce per-process prime counts into process 0.
		LongItemBuf buf = LongBuf.buffer (primeCount.longValue());
		world.reduce (0, buf, LongOp.SUM);

		// Stop timing.
		long t2 = System.currentTimeMillis();

		// Print the answer. (Add 1 because 2 is a prime.)
		if (rank == 0) System.out.println ("pi("+x+") = "+(buf.item + 1));
		System.out.println ((t2-t1)+" msec "+rank);
		}

// Hidden operations.

	/**
	 * Print a usage message and exit.
	 */
	private static void usage()
		{
		System.err.println ("Usage: java -Dpj.np=<Kp> -Dpj.nt=<Kt> [ -Dpj.schedule=<procschedule> ] edu.rit.hyb.prime.PrimeCountFunctionHyb <x> <primefile> [ <thrschedule> ]");
		System.err.println ("<Kp> = Number of parallel processes");
		System.err.println ("<Kt> = Number of parallel threads per process");
		System.err.println ("<procschedule> = Load balancing schedule for processes");
		System.err.println ("<x> = Argument of prime counting function, 0 <= <x> <= 2^63-1");
		System.err.println ("<primefile> = Prime file name");
		System.err.println ("<thrschedule> = Load balancing schedule for threads System.exit (1);");
		}

	}