Semi parallel for loop in Go
Starting with same old sequential for loop.It will iterate through a slice if integers , sum it and print. Note : I’m running this on OS X 10.9,Core i5,4GB.Running on playground might give different time elapsed, probably 0. //Setting concurrency to maximum runtime.GOMAXPROCS(runtime.NumCPU()) j, k := 10, 20 var Dat []int //Sample slice i := 0 for i < 10300 { Dat = append(Dat, i) i++ } //1.Simple for loop Start := time.Now() for i := range Dat { fmt.Println(i + j + k) //Iterating through Dat slice, printing sum.(i is from Dat) } log.Println("Time taken for sequential : ", time.Since(Start)) Here Time taken in my Mac : 12.844223ms Making it parallel (precisely concurrent), using function literals //2.Full parallel loop Start = time.Now() for i := range Dat { go func(i, j, k int) { fmt.Println(i + j + k) }(i, j, k) } log.Println("Time taken with Concurrent Go routines : ", time.Since(Start)) Time taken : 13.199926ms Slight increase in time, but it will depends on hardwares.What I want to prove is simply using Go routines won’t yield maximum throughput. »