-
白衣染霜花
您可以根据 Nipun Talukdar 的评论计算大小。len([]byte("YourDataHere"))b.Len()并使用time.Now()和time.Since()来获取所花费的时间。var b bytes.Bufferinput := []byte("YourDataHere")fmt.Println("Input size : ", len(input))gz := gzip.NewWriter(&b)start := time.Now() gz.Write(input)if _, err := gz.Flush(); err != nil { panic(err)}totalTime := time.Since(start) fmt.Println("Compressed size : ", b.Len(), "\nTime taken : ", totalTime)gz.Close()解压也可以应用相同的方法。您还可以创建一个可以进行计时的支持功能。func timer(startTime time.Time) {totalTime := time.Since(startTime)log.Println("Time taken : ",totalTime)}用法:defer timer(time.Now())在函数的开头。
-
皈依舞
这里有如何在 Go 中执行此操作的示例https://golang.org/test/bench/go1/gzip_test.go谢天谢地,它是 BSD 许可的......// Copyright 2011 The Go Authors. All rights reserved.// Use of this source code is governed by a BSD-style// license that can be found in the LICENSE file.// This benchmark tests gzip and gunzip performance.package go1 import ( "bytes" gz "compress/gzip" "io" "io/ioutil" "testing")var ( jsongunz = bytes.Repeat(jsonbytes, 10) jsongz []byte)func init() { var buf bytes.Buffer c := gz.NewWriter(&buf) c.Write(jsongunz) c.Close() jsongz = buf.Bytes()}func gzip() { c := gz.NewWriter(ioutil.Discard) if _, err := c.Write(jsongunz); err != nil { panic(err) } if err := c.Close(); err != nil { panic(err) }}func gunzip() { r, err := gz.NewReader(bytes.NewBuffer(jsongz)) if err != nil { panic(err) } if _, err := io.Copy(ioutil.Discard, r); err != nil { panic(err) } r.Close()}func BenchmarkGzip(b *testing.B) { b.SetBytes(int64(len(jsongunz))) for i := 0; i < b.N; i++ { gzip() }}func BenchmarkGunzip(b *testing.B) { b.SetBytes(int64(len(jsongunz))) for i := 0; i < b.N; i++ { gunzip() }}
-
一只名叫tom的猫
不幸的是,gzip.Writer无法报告写入底层流的压缩字节数。当底层流不在内存中时,它会变得更加复杂。为了解决这个问题,我写了一个“计数io.Writer”,我把它放在gzip.Writer和底层流之间,这样我就可以计算和提取写入的压缩字节数。在Go Playground 中尝试以下代码。package mainimport ( "compress/gzip" "fmt" "io" "os")// countingWriter is an io.Writer that counts the total bytes written to it.type countingWriter struct { w io.Writer Count int}var _ io.Writer = &countingWriter{}func newCountingWriter(w io.Writer) *countingWriter { return &countingWriter{w: w}}func (cw *countingWriter) Write(p []byte) (int, error) { n, err := cw.w.Write(p) cw.Count += n return n, err}func ExampleUse(w io.Writer) (int, error) { cw := newCountingWriter(w) zw, err := gzip.NewWriterLevel(cw, gzip.BestCompression) if err != nil { return 0, err } if _, err := zw.Write([]byte("hello world")); err != nil { return cw.Count, err } err = zw.Close() return cw.Count, err}func main() { n, err := ExampleUse(os.Stderr) if err != nil { panic(err) } fmt.Printf("wrote %d bytes\n", n)}