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
75 lines (58 loc) · 2.29 KB
/
MonteCarloPi.java
File metadata and controls
75 lines (58 loc) · 2.29 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
import java.util.Random;
import com.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};
Data.randu(x, dims, Array.FloatType);
Data.randu(y, dims, Array.FloatType);
Arith.mul(x, x, x);
Arith.mul(y, y, y);
Arith.add(res, x, y);
Arith.lt(res, res, 1);
double count = Algorithm.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 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) {
System.out.println(e.getMessage());
}
}
}