Skip to content

Instantly share code, notes, and snippets.

@humamfauzi
Created August 8, 2018 11:41
Show Gist options
  • Save humamfauzi/c4e2817e9ebc1035b36d0823576a5107 to your computer and use it in GitHub Desktop.
Save humamfauzi/c4e2817e9ebc1035b36d0823576a5107 to your computer and use it in GitHub Desktop.
Comparing ordinary routine and goroutine execution speed
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