Last active
March 26, 2021 01:19
-
-
Save rysk92/0fd45a42de72c6e99cec2aaea25a42e7 to your computer and use it in GitHub Desktop.
Goroutine の並列性(Parallelism)について検証する
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 ( | |
"crypto/sha256" | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"runtime" | |
"runtime/trace" | |
) | |
func main() { | |
f, err := os.Create("runtime.trace") | |
if err != nil { | |
fmt.Println(err) | |
} | |
trace.Start(f) | |
defer trace.Stop() | |
byForLoop() | |
byGoroutine(1) | |
byGoroutine(4) | |
byGoroutine(runtime.NumCPU()) | |
} | |
func getHash() string { | |
f, err := os.Open("./golang/debian-10.8.0-amd64-netinst.iso") | |
if err != nil { | |
log.Fatal(err) | |
} | |
defer f.Close() | |
h := sha256.New() | |
if _, err := io.Copy(h, f); err != nil { | |
log.Fatal(err) | |
} | |
hash := fmt.Sprintf("%x", h.Sum(nil)) | |
return hash | |
} | |
func getHashByChannel(c chan string) { | |
c <- getHash() | |
} | |
func byForLoop() { | |
loopCount := 30 | |
for i := 0; i < loopCount; i++ { | |
hash := getHash() | |
fmt.Println(hash) | |
} | |
} | |
func byGoroutine(numberOfCPU int) { | |
runtime.GOMAXPROCS(numberOfCPU) | |
c := make(chan string) | |
loopCount := 30 | |
for i := 0; i < loopCount; i++ { | |
go getHashByChannel(c) | |
} | |
for i := 0; i < loopCount; i++ { | |
hash := <-c | |
fmt.Println(hash) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment