concurrent_pi2.go 830 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // concurrent_pi2.go
  2. package main
  3. import (
  4. "fmt"
  5. "math"
  6. "runtime"
  7. "time"
  8. )
  9. const NCPU = 2
  10. func main() {
  11. start := time.Now()
  12. runtime.GOMAXPROCS(2)
  13. fmt.Println(CalculatePi(5000))
  14. end := time.Now()
  15. delta := end.Sub(start)
  16. fmt.Printf("longCalculation took this amount of time: %s\n", delta)
  17. }
  18. func CalculatePi(end int) float64 {
  19. ch := make(chan float64)
  20. for i := 0; i < NCPU; i++ {
  21. go term(ch, i*end/NCPU, (i+1)*end/NCPU)
  22. }
  23. result := 0.0
  24. for i := 0; i < NCPU; i++ {
  25. result += <-ch
  26. }
  27. return result
  28. }
  29. func term(ch chan float64, start, end int) {
  30. result := 0.0
  31. for i := start; i < end; i++ {
  32. x := float64(i)
  33. result += 4 * (math.Pow(-1, x) / (2.0*x + 1.0))
  34. }
  35. ch <- result
  36. }
  37. /* Output:
  38. 3.1413926535917938
  39. The calculation took this amount of time: 0.002000
  40. */