Skip to content

Commit 87ba291

Browse files
committed
Updating the monte carlo pi example
- It now has benchmarks and a host version
1 parent e84cbb7 commit 87ba291

File tree

1 file changed

+31
-3
lines changed

1 file changed

+31
-3
lines changed

examples/monte_carlo_pi.py

Lines changed: 31 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,41 @@
11
#!/usr/bin/python
2+
from random import random
3+
from time import time
24
from arrayfire import (array, randu)
35
import arrayfire as af
4-
import random
6+
7+
#alias range / xrange because xrange is faster than range in python2
8+
try:
9+
frange = xrange #Python2
10+
except NameError:
11+
frange = range #Python3
12+
513

614
def calc_pi_device(samples):
715
x = randu(samples)
816
y = randu(samples)
917
return 4 * af.sum((x * x + y * y) < 1) / samples
1018

19+
# Having the function outside is faster than the lambda inside
20+
def in_circle(x, y):
21+
return (x*x + y*y) < 1
22+
23+
def calc_pi_host(samples):
24+
count = sum(1 for k in frange(samples) if in_circle(random(), random()))
25+
return 4 * float(count) / samples
26+
27+
def bench(calc_pi, samples=1000000, iters=25):
28+
func_name = calc_pi.__name__[8:]
29+
print("Monte carlo estimate of pi on %s with %d million samples: %f" % \
30+
(func_name, samples/1e6, calc_pi(samples)))
31+
32+
start = time()
33+
for k in frange(iters):
34+
calc_pi(samples)
35+
end = time()
36+
37+
print("Average time taken: %f ms" % (1000 * (end - start) / iters))
38+
1139
if __name__ == "__main__":
12-
samples=1000000
13-
print("Monte carlo estimate of pi with %d samples: %f" % (samples, calc_pi_device(samples)))
40+
bench(calc_pi_device)
41+
bench(calc_pi_host)

0 commit comments

Comments
 (0)