Skip to content

Instantly share code, notes, and snippets.

@aarti
Created December 16, 2016 18:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarti/b55b3fa55d18bfaea8ae6b510e500fa8 to your computer and use it in GitHub Desktop.
Save aarti/b55b3fa55d18bfaea8ae6b510e500fa8 to your computer and use it in GitHub Desktop.
/*
Design a Rate Printer
The printer reads from a file
The printer writes to a file
Print the Bytes/Second at which the printer is printing every second
*/
package main
import (
"fmt"
"io"
"log"
"os"
"time"
)
var dataread chan int
var data chan []byte
func main() {
dataread = make(chan int, 100)
data = make(chan []byte, 100)
go reader("/dev/zero")
go writer("/dev/null")
totalBytes := 0
start := time.Now()
var t time.Time
var rate float64
var diff time.Duration
for {
d := <-dataread
totalBytes += d
t = time.Now()
diff = t.Sub(start)
if diff > 1*time.Second {
rate = float64(totalBytes) / (float64(diff) / float64(time.Second))
fmt.Println("Rate: Bytes/Second", rate)
start = t
}
}
}
func reader(s string) {
var err error
rc, err := os.Open(s)
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 10)
for {
if _, err = io.ReadAtLeast(rc, buf, 4); err != nil {
log.Fatal(err)
}
dataread <- len(buf)
data <- buf
buf = make([]byte, 10)
}
}
func writer(f string) {
for {
<-data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment