dongmi5015 2016-04-19 03:00
浏览 48
已采纳

如何在压缩之前和之后测量字节大小和时间

I want to gzip a string (it is actually a JSON response)

var b bytes.Buffer
gz := gzip.NewWriter(&b)
if _, err := gz.Write([]byte("YourDataHere")); err != nil {
    panic(err)
}

How can I easily output the size of bytes before and after compression and more importantly how can I time it takes to compress and decompress back to a string?

  • 写回答

2条回答 默认 最新

  • douhuijun3776 2016-04-19 04:19
    关注

    You can calculate the size as per Nipun Talukdar's comment.

    len([]byte("YourDataHere")) b.Len()

    And use time.Now() and time.Since() to get the time taken.

    var b bytes.Buffer
    input := []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(), "
    Time taken : ", totalTime)
    gz.Close()
    

    Same method can be applied with unzipping. You can also create a support function that can do the timing.

    func timer(startTime time.Time) {
    
    totalTime := time.Since(startTime)
    log.Println("Time taken : ",totalTime)
    
    }
    

    Usage : defer timer(time.Now()) at the start of the function.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题