I just write a simple go1 command project to test. My full code is here.
My test environment:
Linux home 3.2.0-29-generic #46-Ubuntu SMP Fri Jul 27 17:03:23 UTC 2012
x86_64 x86_64 x86_64 GNU/Linux
// binarywrite project main.go
package main
import (
"bufio"
"encoding/binary"
"flag"
"fmt"
"os"
"time"
"unsafe"
"runtime"
"log"
)
// Checkf call os.Exit(1) if err != nil
func Checkf(err error, format string, arg ...interface{}) {
if err != nil {
_, file, line, _ := runtime.Caller(1)
log.Fatalf("%s:%v:%s, %s",
file, line, err, fmt.Sprintf(format, arg))
}
}
type Action struct {
U1 uint64
U2 uint64
U3 uint64
}
func main() {
var (
filePath string
bufSize int
fileSize uint64
)
flag.StringVar(&filePath, "file", "", "file path")
flag.IntVar(&bufSize, "buffer_size", 4096, "buffer size")
flag.Uint64Var(&fileSize, "size", 1024*1024, "file size")
flag.Usage = func() {
fmt.Printf("Usage: %s [Options]\n", os.Args[0])
flag.PrintDefaults()
}
flag.Parse()
if filePath == "" {
flag.Usage()
return
}
f, err := os.Create(filePath)
Checkf(err, "create file %s failed", filePath)
defer f.Close()
var totalSize uint64
w := bufio.NewWriter(f)
tStart := time.Now()
var action Action
for totalSize < fileSize {
Checkf(binary.Write(w, binary.LittleEndian, &action), "write %v", totalSize)
totalSize += uint64(unsafe.Sizeof(action))
}
tStop := time.Now()
tDuration := tStop.Sub(tStart)
fmt.Printf("Write over, totalSize: %v, time elapsed: %v(s), speed: %v MB/s
\n",
totalSize,
tDuration.Seconds(),
float64(totalSize/1048576)/tDuration.Seconds())
}
On Thu, Nov 8, 2012 at 1:04 AM, Dustin Sallings wrote:go-fish <
[email protected]> writes:
i use encoding/binary package for testing the binary write/read speed,
but it reach 12MB/s at most.
What is the fastest way to read/write binary file using go?
f, _ := os.Create("test")
defer f.Close()
w := bufio.NewWriter(f)
var action Action
for {
binary.Write(w, binary.LittleEndian, &action)
}
Can you post a usable benchmark? I don't find it slowing me down
excessively in gomemcached doing binary protocol encoding (first
real-world use case I could think of in my groggy state on the train):
BenchmarkEncodingRequest 10000000 243 ns/op 163.97
MB/s
BenchmarkEncodingRequest0CAS 10000000 240 ns/op 166.23
MB/s
BenchmarkEncodingRequest1Extra 10000000 234 ns/op 174.65
MB/s
BenchmarkEncodingResponse 10000000 234 ns/op 170.27
MB/s
BenchmarkEncodingResponseLarge 500000 6280 ns/op 3917.74
MB/s
--
dustin
--
--