Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created July 11, 2018 06:57
Show Gist options
  • Save yowcow/66d06d1cebba3da6bcca0ee8be384ebe to your computer and use it in GitHub Desktop.
Save yowcow/66d06d1cebba3da6bcca0ee8be384ebe to your computer and use it in GitHub Desktop.
JSON unmarshal serial v. parallel
package main
import (
"encoding/json"
"sync"
"testing"
)
var jsonStr = `{"url":"http://hoge","score":123,"map":{"123":123,"234":234}}`
type Map map[string]int
type Source struct {
URL string `json:"url"`
Score int `json:"score"`
Map Map `json:"map"`
}
func BenchmarkSerial_JSON_Unmarshal(b *testing.B) {
jsonBytes := []byte(jsonStr)
b.ResetTimer()
for i := 0; i < b.N; i++ {
var src Source
json.Unmarshal(jsonBytes, &src)
}
b.StopTimer()
}
func BenchmarkParallel_JSON_Unmarshal(b *testing.B) {
jsonBytes := []byte(jsonStr)
var wg sync.WaitGroup
out := make(chan []byte)
wg.Add(5)
for i := 0; i < 5; i++ {
go func(w *sync.WaitGroup, in <-chan []byte) {
defer w.Done()
for input := range in {
var src Source
json.Unmarshal(input, &src)
}
}(&wg, out)
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
out <- jsonBytes
}
b.StopTimer()
close(out)
wg.Wait()
}
/**
BenchmarkSerial_JSON_Unmarshal-4 300000 4265 ns/op
BenchmarkParallel_JSON_Unmarshal-4 500000 3024 ns/op
*/
@yowcow
Copy link
Author

yowcow commented Jul 11, 2018

% cat /proc/cpuinfo | grep ^processor | wc -l
4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment