-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathMonteCarloPi.java
More file actions
79 lines (62 loc) · 2 KB
/
MonteCarloPi.java
File metadata and controls
79 lines (62 loc) · 2 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
74
75
76
77
78
79
import java.util.Random;
import com.arrayfire.*;
import static com.arrayfire.ArrayFire.*;
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 = new Array(), y = new Array(), res = new Array();
try {
int[] dims = new int[] { size, 1 };
randu(x, dims, Type.Float);
randu(y, dims, Type.Float);
mul(x, x, x);
mul(y, y, y);
add(res, x, y);
lt(res, res, 1);
double count = sumAll(res);
return 4.0 * ((double) (count)) / size;
} catch (Exception e) {
throw e;
} finally {
x.close();
y.close();
res.close();
}
}
public static void main(String[] args) {
try {
int size = 5000000;
int iter = 100;
double devicePi = deviceCalcPi(size);
System.out.println("Results from device: " + devicePi);
double hostPi = hostCalcPi(size);
System.out.println("Results from host: " + hostPi);
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 device (ms): " + deviceElapsed);
long hostStart = System.currentTimeMillis();
for (int i = 0; i < iter; i++) {
hostPi = hostCalcPi(size);
}
double hostElapsed = (double) (System.currentTimeMillis() - hostStart) / iter;
System.out.println("Time taken for host (ms): " + hostElapsed);
System.out.println("Speedup: " + Math.round((hostElapsed) / (deviceElapsed)));
} catch (Exception e) {
e.printStackTrace();
}
}
}