-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.java
More file actions
64 lines (50 loc) · 2.04 KB
/
Copy pathMain.java
File metadata and controls
64 lines (50 loc) · 2.04 KB
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
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
import static java.lang.Math.cos;
import static java.lang.Math.sin;
public class Main {
static final int SIZE = 10000000;
public static void main(String[] args) {
System.out.println("Time of serial method: " + countArraySerial());
System.out.println("Time of parallel method: " + countArrayParallel());
}
private static long countArraySerial() {
float[] arr = new float[SIZE];
for (int i=0; i<SIZE; i++)
arr[i] = 1;
long beginTiming = System.currentTimeMillis();
for (int i=0; i<SIZE; i++) {
arr[i] = (float)(arr[i] * sin(0.2f+i/5.0f) * cos(0.2f+i/5.0f) * cos(0.4f+i/2.0f));
}
return System.currentTimeMillis() - beginTiming;
}
private static long countArrayParallel() {
float[] arr = new float[SIZE];
float[] a1 = new float[SIZE/2];
float[] a2 = new float[SIZE/2];
int h = SIZE/2;
for (int i=0; i<SIZE; i++)
arr[i] = 1;
long beginTiming = System.currentTimeMillis();
System.arraycopy(arr,0,a1,0,h);
System.arraycopy(arr,h,a2,0,h);
//создаем пул с двумя потоками
ExecutorService executor = Executors.newFixedThreadPool(2);
List<Future<float[]>> list = new ArrayList<>();
CallableCounter thread1 = new CallableCounter(a1,0);
CallableCounter thread2 = new CallableCounter(a2,1);
//вычисляем результаты свободными потоками
list.add(executor.submit(thread1));
list.add(executor.submit(thread2));
//соединяем результаты
try {
System.arraycopy(list.get(0).get(),0,arr,0,h);
System.arraycopy(list.get(1).get(),0,arr,h,h);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
executor.shutdown();
return System.currentTimeMillis() - beginTiming;
}
}