File tree Expand file tree Collapse file tree 1 file changed +31
-3
lines changed
Expand file tree Collapse file tree 1 file changed +31
-3
lines changed Original file line number Diff line number Diff line change 11#!/usr/bin/python
2+ from random import random
3+ from time import time
24from arrayfire import (array , randu )
35import 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
614def 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+
1139if __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 )
You can’t perform that action at this time.
0 commit comments