forked from arrayfire/arrayfire-java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMonteCarloPi.java
More file actions
73 lines (58 loc) · 2.27 KB
/
MonteCarloPi.java
File metadata and controls
73 lines (58 loc) · 2.27 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
65
66
67
68
69
70
71
72
73
import java.util.Random;
import com.arrayfire.Array;
public class MonteCarloPi {
public static double hostCalcPi(int size) {
Random rand = new Random();
int count = 0;
for (int i = 0; i < size; i++) {
float x = rand.nextFloat();
float y = rand.nextFloat();
boolean lt1 = (x * x + y * y) < 1;
if (lt1) count++;
}
return 4.0 * ((double)(count)) / size;
}
public static double deviceCalcPi(int size) throws Exception {
Array x = null, y = null, res = null;
try {
int[] dims = new int[] {size, 1};
x = Array.randu(dims, Array.FloatType);
y = Array.randu(dims, Array.FloatType);
x = Array.mul(x, x);
y = Array.mul(y, y);
res = Array.add(x , y);
res = Array.lt(res, 1);
double count = Array.sumAll(res);
return 4.0 * ((double)(count)) / size;
} finally {
if (x != null) x.close();
if (y != null) y.close();
if (res != null) res.close();
}
}
public static void main(String[] args) {
try {
int size = 5000000;
int iter = 100;
double hostPi = hostCalcPi(size);
double devicePi = deviceCalcPi(size);
System.out.println("Results from host: " + hostPi);
System.out.println("Results from device: " + devicePi);
long hostStart = System.currentTimeMillis();
for (int i = 0; i < iter; i++) {
hostPi = hostCalcPi(size);
}
double hostElapsed = (double)(System.currentTimeMillis() - hostStart)/iter;
long deviceStart = System.currentTimeMillis();
for (int i = 0; i < iter; i++) {
devicePi = deviceCalcPi(size);
}
double deviceElapsed = (double)(System.currentTimeMillis() - deviceStart)/iter;
System.out.println("Time taken for host (ms): " + hostElapsed);
System.out.println("Time taken for device (ms): " + deviceElapsed);
System.out.println("Speedup: " + Math.round((hostElapsed) / (deviceElapsed)));
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}