Created
June 24, 2017 23:23
-
-
Save scukonick/0c6561b9fe4775d17785bb807b54821c to your computer and use it in GitHub Desktop.
Comparsion of channels ws file per goroutine
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 file_watcher | |
import ( | |
"fmt" | |
"io" | |
"log" | |
"os" | |
"strings" | |
"sync" | |
"testing" | |
) | |
func filePerRouting() { | |
wg := sync.WaitGroup{} | |
t := log.Logger{} | |
for i := 0; i < 1000; i++ { | |
wg.Add(1) | |
go func(number int) { | |
f, err := os.OpenFile("/tmp/test.file.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) | |
if err != nil { | |
t.Fatal(err) | |
} | |
for j := 0; j < 1000; j++ { | |
r := strings.NewReader(fmt.Sprintf("goroutine: %d, loop: %d\n", number, j)) | |
_, err = io.Copy(f, r) | |
if err != nil { | |
t.Fatal(err) | |
} | |
} | |
err = f.Close() | |
if err != nil { | |
t.Fatal(f) | |
} | |
wg.Done() | |
}(i) | |
} | |
wg.Wait() | |
} | |
func withChanel() { | |
t := log.Logger{} | |
wg := sync.WaitGroup{} | |
ch := make(chan string, 0) | |
wg.Add(1) | |
go func(input chan string) { | |
f, err := os.OpenFile("/tmp/test.file.log", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644) | |
if err != nil { | |
t.Fatal(err) | |
} | |
for x := range input { | |
r := strings.NewReader(x) | |
_, err = io.Copy(f, r) | |
if err != nil { | |
t.Fatal(err) | |
} | |
} | |
err = f.Close() | |
if err != nil { | |
t.Fatal(f) | |
} | |
wg.Done() | |
}(ch) | |
tokens := make(chan bool, 1000) | |
for i := 0; i < 1000; i++ { | |
wg.Add(1) | |
go func(number int, c chan string) { | |
for j := 0; j < 1000; j++ { | |
c <- fmt.Sprintf("goroutine: %d, loop: %d\n", number, j) | |
} | |
// signaling about exit | |
tokens <- true | |
wg.Done() | |
}(i, ch) | |
} | |
// closing channel after all goroutins exit | |
for i := 0; i < 1000; i++ { | |
<-tokens | |
} | |
close(ch) | |
wg.Wait() | |
} | |
func BenchmarkFilePerRoutine(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
filePerRouting() | |
} | |
} | |
func BenchmarkWithChannel(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
withChanel() | |
} | |
} | |
/* | |
1 1334103459 ns/op | |
1 1743324112 ns/op | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment