欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Go語言中三種不同md5計(jì)算方式的性能比較

 更新時間:2017年01月04日 14:57:37   作者:holys''''''''  
md5計(jì)算在我們?nèi)粘9ぷ鞯臅r候經(jīng)常能遇到,下面這篇文章主要介紹了Go語言中三種不同md5計(jì)算方式的性能比較,需要的朋友可以參考借鑒,下面來一起學(xué)習(xí)學(xué)習(xí)吧。

前言

本文主要介紹的是三種不同的 md5 計(jì)算方式,其實(shí)區(qū)別是讀文件的不同,也就是磁盤 I/O, 所以也可以舉一反三用在網(wǎng)絡(luò) I/O 上。下面來一起看看吧。

ReadFile

先看第一種, 簡單粗暴:

func md5sum1(file string) string {
 data, err := ioutil.ReadFile(file)
 if err != nil {
 return ""
 }

 return fmt.Sprintf("%x", md5.Sum(data))
}

之所以說其粗暴,是因?yàn)?ReadFile 里面其實(shí)調(diào)用了一個 readall, 分配內(nèi)存是最多的。

Benchmark 來一發(fā):

var test_path = "/path/to/file"
func BenchmarkMd5Sum1(b *testing.B) {
 for i := 0; i < b.N; i++ {
 md5sum1(test_path)
 }
}
go test -test.run=none -test.bench="^BenchmarkMd5Sum1$" -benchtime=10s -benchmem

BenchmarkMd5Sum1-4 300 43704982 ns/op 19408224 B/op 14 allocs/op
PASS
ok tmp 17.446s

先說明下,這個文件大小是 19405028 字節(jié),和上面的 19408224 B/op 非常接近, 因?yàn)?readall 確實(shí)是分配了文件大小的內(nèi)存,代碼為證:

ReadFile 源碼

// ReadFile reads the file named by filename and returns the contents.
// A successful call returns err == nil, not err == EOF. Because ReadFile
// reads the whole file, it does not treat an EOF from Read as an error
// to be reported.
func ReadFile(filename string) ([]byte, error) {
 f, err := os.Open(filename)
 if err != nil {
 return nil, err
 }
 defer f.Close()
 // It's a good but not certain bet that FileInfo will tell us exactly how much to
 // read, so let's try it but be prepared for the answer to be wrong.
 var n int64

 if fi, err := f.Stat(); err == nil {
 // Don't preallocate a huge buffer, just in case.
 if size := fi.Size(); size < 1e9 {
 n = size
 }
 }
 // As initial capacity for readAll, use n + a little extra in case Size is zero,
 // and to avoid another allocation after Read has filled the buffer. The readAll
 // call will read into its allocated internal buffer cheaply. If the size was
 // wrong, we'll either waste some space off the end or reallocate as needed, but
 // in the overwhelmingly common case we'll get it just right.
 
 // readAll 第二個參數(shù)是即將創(chuàng)建的 buffer 大小
 return readAll(f, n+bytes.MinRead)
}

func readAll(r io.Reader, capacity int64) (b []byte, err error) {
 // 這個 buffer 的大小就是 file size + bytes.MinRead 

 buf := bytes.NewBuffer(make([]byte, 0, capacity))
 // If the buffer overflows, we will get bytes.ErrTooLarge.
 // Return that as an error. Any other panic remains.
 defer func() {
 e := recover()
 if e == nil {
 return
 }
 if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
 err = panicErr
 } else {
 panic(e)
 }
 }()
 _, err = buf.ReadFrom(r)
 return buf.Bytes(), err
}

io.Copy

再看第二種,

func md5sum2(file string) string {
 f, err := os.Open(file)
 if err != nil {
 return ""
 }
 defer f.Close()

 h := md5.New()

 _, err = io.Copy(h, f)
 if err != nil {
 return ""
 }

 return fmt.Sprintf("%x", h.Sum(nil))
}

第二種的特點(diǎn)是:使用了 io.Copy。 在一般情況下(特殊情況在下面會提到),io.Copy 每次會分配 32 *1024 字節(jié)的內(nèi)存,即32 KB, 然后咱看下 Benchmark 的情況:

func BenchmarkMd5Sum2(b *testing.B) {

 for i := 0; i < b.N; i++ {
 md5sum2(test_path)
 }
}
$ go test -test.run=none -test.bench="^BenchmarkMd5Sum2$" -benchtime=10s -benchmem

BenchmarkMd5Sum2-4 500 37538305 ns/op 33093 B/op 8 allocs/op
PASS
ok tmp 22.657s

32 * 1024 = 32768, 和 上面的 33093 B/op 很接近。

io.Copy + bufio.Reader

然后再看看第三種情況。

這次不僅用了 io.Copy,還用了 bufio.Reader。 bufio 顧名思義, 即 buffered I/O, 性能相對要好些。bufio.Reader 默認(rèn)會創(chuàng)建 4096 字節(jié)的 buffer。

func md5sum3(file string) string {
 f, err := os.Open(file)
 if err != nil {
 return ""
 }
 defer f.Close()
 r := bufio.NewReader(f)

 h := md5.New()

 _, err = io.Copy(h, r)
 if err != nil {
 return ""
 }

 return fmt.Sprintf("%x", h.Sum(nil))

}

看下 Benchmark 的情況:

func BenchmarkMd5Sum3(b *testing.B) {
 for i := 0; i < b.N; i++ {
 md5sum3(test_path)
 }
}
$ go test -test.run=none -test.bench="^BenchmarkMd5Sum3$" -benchtime=10s -benchmem
BenchmarkMd5Sum3-4 300 42589812 ns/op 4507 B/op 9 allocs/op
PASS
ok tmp 16.817s

上面的 4507 B/op 是不是和 4096 很接近? 那為什么 io.Copy + bufio.Reader 的方式所用內(nèi)存會比單純的 io.Copy 占用內(nèi)存要少一些呢? 上文也提到, 一般情況下 io.Copy 每次會分配 32 *1024 字節(jié)的內(nèi)存,那特殊情況是? 答案在源碼中。

一起看看 io.Copy 相關(guān)源碼:

func Copy(dst Writer, src Reader) (written int64, err error) {
 return copyBuffer(dst, src, nil)
}

// copyBuffer is the actual implementation of Copy and CopyBuffer.
// if buf is nil, one is allocated.
func copyBuffer(dst Writer, src Reader, buf []byte) (written int64, err error) {
 // If the reader has a WriteTo method, use it to do the copy.
 // Avoids an allocation and a copy.

 // hash.Hash 這個 Writer 并沒有實(shí)現(xiàn) WriteTo 方法,所以不會走這里
 if wt, ok := src.(WriterTo); ok {
 return wt.WriteTo(dst)
 }
 // Similarly, if the writer has a ReadFrom method, use it to do the copy.
 // 而 bufio.Reader 實(shí)現(xiàn)了 ReadFrom 方法,所以,會走這里
 if rt, ok := dst.(ReaderFrom); ok {
 return rt.ReadFrom(src)
 }
 
 if buf == nil {
 buf = make([]byte, 32*1024)
 }
 for {
 nr, er := src.Read(buf)
 if nr > 0 {
 nw, ew := dst.Write(buf[0:nr])
 if nw > 0 {
 written += int64(nw)
 }
 if ew != nil {
 err = ew
 break
 }
 if nr != nw {
 err = ErrShortWrite
 break
 }
 }
 if er == EOF {
 break
 }
 if er != nil {
 err = er
 break
 }
 }
 return written, err
}

從上面的源碼來看, 用 bufio.Reader 實(shí)現(xiàn)的 io.Reader 并不會走默認(rèn)的 buffer創(chuàng)建路徑,而是提前返回了,使用了 bufio.Reader 創(chuàng)建的 buffer, 這也是使用了 bufio.Reader 分配的內(nèi)存會小一些。

當(dāng)然如果你希望 io.Copy 也分配小一點(diǎn)的內(nèi)存,也是可以做到的,不過是用 io.CopyBuffer, buf 就創(chuàng)建一個 4096 的 []byte 即可, 就跟 bufio.Reader 區(qū)別不大了。

看看是不是這樣:

// Md5Sum2 用 CopyBufer 重新實(shí)現(xiàn),buf := make([]byte, 4096)
BenchmarkMd5Sum2-4  500 38484425 ns/op 4409 B/op  8 allocs/op
BenchmarkMd5Sum3-4  500 38671090 ns/op 4505 B/op  9 allocs/op

從結(jié)果來看, 分配的內(nèi)存相差不大,畢竟實(shí)現(xiàn)不一樣,不可能一致。

那下次如果你要寫一個下載大文件的程序,你還會用 ioutil.ReadAll(resp.Body) 嗎?

最后整體對比下 Benchmark 的情況:

$ go test -test.run=none -test.bench="." -benchtime=10s -benchmem
testing: warning: no tests to run
BenchmarkMd5Sum1-4  300 42551920 ns/op 19408230 B/op  14 allocs/op
BenchmarkMd5Sum2-4  500 38445352 ns/op 33089 B/op  8 allocs/op
BenchmarkMd5Sum3-4  500 38809429 ns/op 4505 B/op  9 allocs/op
PASS
ok tmp 63.821s

小結(jié)

這三種不同的 md5 計(jì)算方式在執(zhí)行時間上都差不多,區(qū)別最大的是內(nèi)存的分配上;

bufio 在處理 I/O 還是很有優(yōu)勢的,優(yōu)先選擇;

盡量避免 ReadAll 這種用法。

總結(jié)

以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。

相關(guān)文章

  • Go語言基礎(chǔ)單元測試與性能測試示例詳解

    Go語言基礎(chǔ)單元測試與性能測試示例詳解

    這篇文章主要為大家介紹了Go語言基礎(chǔ)單元測試與性能測試示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進(jìn)步
    2021-11-11
  • Golang動態(tài)數(shù)組的實(shí)現(xiàn)示例

    Golang動態(tài)數(shù)組的實(shí)現(xiàn)示例

    動態(tài)數(shù)組能自動調(diào)整大小,與靜態(tài)數(shù)組不同,其大小不固定,可根據(jù)需求變化,實(shí)現(xiàn)通常依賴于數(shù)據(jù)結(jié)構(gòu)如鏈表或數(shù)組加額外信息,本文就來介紹一下Golang動態(tài)數(shù)組的實(shí)現(xiàn)示例,感興趣的可以了解一下
    2024-10-10
  • GO語言基本類型分析

    GO語言基本類型分析

    這篇文章主要介紹了GO語言基本類型,較為詳細(xì)的分析了整形、浮點(diǎn)型、字符串、指針等類型的具體用法,是深入學(xué)習(xí)GO語言所必須掌握的重要基礎(chǔ),需要的朋友可以參考下
    2014-12-12
  • go語言channel實(shí)現(xiàn)多核并行化運(yùn)行的方法

    go語言channel實(shí)現(xiàn)多核并行化運(yùn)行的方法

    這篇文章主要介紹了go語言channel實(shí)現(xiàn)多核并行化運(yùn)行的方法,實(shí)例分析了channel實(shí)現(xiàn)多核并行化運(yùn)行的技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下
    2015-03-03
  • Go語言中sync.Mutex的使用方法

    Go語言中sync.Mutex的使用方法

    本文主要介紹了golang中sync.Mutex的實(shí)現(xiàn)方法,mutex主要有兩個 method:Lock()和Unlock(),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2023-03-03
  • go xorm存庫處理null值問題

    go xorm存庫處理null值問題

    這篇文章主要介紹了go xorm存庫處理null值問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-12-12
  • 詳解Go語言如何對數(shù)據(jù)庫進(jìn)行CRUD操作

    詳解Go語言如何對數(shù)據(jù)庫進(jìn)行CRUD操作

    在這篇文章中,主要帶大家來學(xué)習(xí)一下在Go語言中如何對數(shù)據(jù)庫進(jìn)行CRUD操作,從而探討一下Go的接口編程,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下
    2023-05-05
  • Go語言基礎(chǔ)函數(shù)包的使用學(xué)習(xí)

    Go語言基礎(chǔ)函數(shù)包的使用學(xué)習(xí)

    本文通過一個實(shí)現(xiàn)加減乘除運(yùn)算的小程序來介紹go函數(shù)的使用,以及使用函數(shù)的注意事項(xiàng),并引出了對包的了解和使用,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2023-05-05
  • 使用Go重構(gòu)流式日志網(wǎng)關(guān)的實(shí)戰(zhàn)分享

    使用Go重構(gòu)流式日志網(wǎng)關(guān)的實(shí)戰(zhàn)分享

    流式日志網(wǎng)關(guān)的主要功能是提供?HTTP?接口,接收?CDN?邊緣節(jié)點(diǎn)上報(bào)的各類日志(訪問日志/報(bào)錯日志/計(jì)費(fèi)日志等),將日志作預(yù)處理并分流到多個的?Kafka?集群和?Topic?中,本文就給大家分享如何使用?Go?重構(gòu)流式日志網(wǎng)關(guān)
    2023-06-06
  • Go讀取配置文件的方法總結(jié)

    Go讀取配置文件的方法總結(jié)

    我們常見的配置文件的格式一般有:XML、JSON、INI、YAML、env和.properties,本文小編為大家整理了Go語言讀取這些格式的配置文件的方法,希望對大家有所幫助
    2023-10-10

最新評論