Created
August 8, 2018 11:41
-
-
Save humamfauzi/c4e2817e9ebc1035b36d0823576a5107 to your computer and use it in GitHub Desktop.
Comparing ordinary routine and goroutine execution speed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"math/rand" | |
"time" | |
"log" | |
) | |
func randomArray(n int) []int { | |
array := make([]int, n) | |
for i := 0; i < n; i++ { | |
array[i] = rand.Intn(10) | |
} | |
return array | |
} | |
func randomArrayChannel(n int) []int { | |
array := make([]int, n) | |
go func(){ | |
for i := 0; i < n; i++ { | |
array[i] = rand.Intn(10) | |
} | |
}() | |
return array | |
} | |
func main() { | |
size := 50000000 | |
start := time.Now() | |
_ = randomArray(size) | |
log.Printf("Ordinary Random Array takes %s", time.Since(start)) | |
start = time.Now() | |
_ = randomArrayChannel(size) | |
log.Printf("Goroutine Random Array takes %s", time.Since(start)) | |
} | |
// In my computer goroutine 18 times faster than ordinary routine; different computer may generate different result |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment