1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
| package main
import ( "fmt" "time" )
func main() { singleCoroutine() multiCoroutine() }
func singleCoroutine() { var result, i uint64 start := time.Now() for i = 1; i <= 10000000000; i++ { result += i } elapsed := time.Since(start) fmt.Println(elapsed, result) }
func multiCoroutine() { var result uint64 start := time.Now() ch1 := calc(1, 2500000000) ch2 := calc(2500000001, 5000000000) ch3 := calc(5000000001, 7500000000) ch4 := calc(7500000001, 10000000000) result = <-ch1 + <-ch2 + <-ch3 + <-ch4 elapsed := time.Since(start) fmt.Println(elapsed, result) }
func calc(from uint64, to uint64) <-chan uint64 { channel := make(chan uint64) go func() { result := from for i := from + 1; i <= to; i++ { result += i } channel <- result }() return channel }
|