[python-arrayfire] 18/250: Updating the monte carlo pi example
Ghislain Vaillant
ghisvail-guest at moszumanska.debian.org
Mon Mar 28 22:59:26 UTC 2016
This is an automated email from the git hooks/post-receive script.
ghisvail-guest pushed a commit to branch debian/master
in repository python-arrayfire.
commit 87ba2911a06bd89208d66868d1b4f18fa539552f
Author: Pavan Yalamanchili <pavan at arrayfire.com>
Date: Mon Jun 22 10:01:39 2015 -0400
Updating the monte carlo pi example
- It now has benchmarks and a host version
---
examples/monte_carlo_pi.py | 34 +++++++++++++++++++++++++++++++---
1 file changed, 31 insertions(+), 3 deletions(-)
diff --git a/examples/monte_carlo_pi.py b/examples/monte_carlo_pi.py
index cf03c9a..80471c9 100644
--- a/examples/monte_carlo_pi.py
+++ b/examples/monte_carlo_pi.py
@@ -1,13 +1,41 @@
#!/usr/bin/python
+from random import random
+from time import time
from arrayfire import (array, randu)
import arrayfire as af
-import random
+
+#alias range / xrange because xrange is faster than range in python2
+try:
+ frange = xrange #Python2
+except NameError:
+ frange = range #Python3
+
def calc_pi_device(samples):
x = randu(samples)
y = randu(samples)
return 4 * af.sum((x * x + y * y) < 1) / samples
+# Having the function outside is faster than the lambda inside
+def in_circle(x, y):
+ return (x*x + y*y) < 1
+
+def calc_pi_host(samples):
+ count = sum(1 for k in frange(samples) if in_circle(random(), random()))
+ return 4 * float(count) / samples
+
+def bench(calc_pi, samples=1000000, iters=25):
+ func_name = calc_pi.__name__[8:]
+ print("Monte carlo estimate of pi on %s with %d million samples: %f" % \
+ (func_name, samples/1e6, calc_pi(samples)))
+
+ start = time()
+ for k in frange(iters):
+ calc_pi(samples)
+ end = time()
+
+ print("Average time taken: %f ms" % (1000 * (end - start) / iters))
+
if __name__ == "__main__":
- samples=1000000
- print("Monte carlo estimate of pi with %d samples: %f" % (samples, calc_pi_device(samples)))
+ bench(calc_pi_device)
+ bench(calc_pi_host)
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-science/packages/python-arrayfire.git
More information about the debian-science-commits
mailing list