Commits

John Floren committed a8f86f7

fixed parallelism issues, added flags

Comments (0)

Files changed (2)

pi/parallel/pi.go

 package main
 
 import (
+	"flag"
 	"fmt"
-	"flag"
 	"math/rand"
 	"time"
 )
 
 var nproc = flag.Int("nproc", 10, "Number of goroutines to spawn")
+var npoints = flag.Int("npoints", 100000000, "Number of points throw, total")
 
 func main() {
 	flag.Parse()
 
-	npoints := 100000000
 	circle_count := 0
 
 	done := make(chan int, *nproc)
 
 	start := time.Now()
 	for i := 0; i < *nproc; i++ {
-		go func(n, seed int, done chan int){
+		go func(n, seed int, done chan int) {
 			r := rand.New(rand.NewSource(int64(seed)))
 			fmt.Printf("starting to calculate %v points\n", n)
 			count := 0
 				x := r.Float64()
 				y := r.Float64()
 
-				if ((x*x) + (y*y)) <= 1.0 {
+				if ((x * x) + (y * y)) <= 1.0 {
 					count++
 				}
 			}
-			done<- count
-		}(npoints/(*nproc), i, done)
+			done <- count
+		}(*npoints/(*nproc), i, done)
 	}
 	for i := 0; i < *nproc; i++ {
 		circle_count += <-done
 	}
 	end := time.Now()
 
-	pi := 4.0 * float64(circle_count)/float64(npoints)
+	pi := 4.0 * float64(circle_count) / float64(*npoints)
 	fmt.Printf("Pi is %v, took %v to run\n", pi, end.Sub(start))
 }
 package main
 
 import (
+	"flag"
 	"fmt"
 	"math/rand"
 	"time"
 )
 
+var npoints = flag.Int("npoints", 100000000, "Number of points throw, total")
+
 func main() {
-	npoints := 100000000
+	flag.Parse()
 	circle_count := 0
 
 	start := time.Now()
-	for i := 0; i < npoints; i++ {
+	for i := 0; i < *npoints; i++ {
 		x := rand.Float64()
 		y := rand.Float64()
 
-		if ((x*x) + (y*y)) <= 1.0 {
+		if ((x * x) + (y * y)) <= 1.0 {
 			circle_count++
 		}
 	}
 	end := time.Now()
 
-	pi := 4.0 * float64(circle_count)/float64(npoints)
+	pi := 4.0 * float64(circle_count) / float64(*npoints)
 	fmt.Printf("Pi is %v, took %v to run\n", pi, end.Sub(start))
 }