近期有一个需求:获取多个文件 md5 校验和判断是否存在重复文件,因为文件数量较多,有的文件还比较大,需要处理的文件还没有到位,我就考虑了一下效率的问题。目前我已知的 Golang 中获取 md5 校验和的方法有两个,这里直接给出实现源码。
package main
import (
"crypto/md5"
"flag"
"fmt"
"io"
"io/IoUtil"
"os"
)
var which = flag.Bool("which",true,"")
var path = flag.String("path","","")
var cnt = flag.Int("cnt", 100,"")
func aaa() {
f,err := os.Open(*path)
if err != nil {
fmt.Println("Open",err)
return
}
defer f.Close()
body,err := IoUtil.ReadAll(f)
if err != nil {
fmt.Println("ReadAll",err)
return
}
md5.Sum(body)
//fmt.Printf("%x\n",md5.Sum(body))
}
func bbb() {
f,err)
return
}
defer f.Close()
md5hash := md5.New()
if _,err := io.Copy(md5hash,f); err != nil {
fmt.Println("Copy",err)
return
}
md5hash.Sum(nil)
//fmt.Printf("%x\n",md5hash.Sum(nil))
}
func main() {
flag.Parse()
for i := 0; i < *cnt; i++ {
if *which {
aaa()
} else {
bbb()
}
}
}
还有可供参考的获取 md5 校验和的 Shell 命令
md5 -- calculate a message-digest fingerprint (checksum) for a file
md5 [-pqrtx] [-s string] [file ...]
banjakukutekiiMac:shell panshiqu$ ls -an | grep by
-rw-r--r-- 1 501 20 7285957 11 17 16:14 by.out
banjakukutekiiMac:shell panshiqu$ cp by.out by2.out
banjakukutekiiMac:shell panshiqu$ cat by.out >> by2.out
banjakukutekiiMac:shell panshiqu$ ls -an | grep by
-rw-r--r-- 1 501 20 7285957 11 17 16:14 by.out
-rw-r--r-- 1 501 20 14571914 11 17 17:03 by2.out
下面效率展示
banjakukutekiiMac:shell panshiqu$ time ./gomd5 -cnt=1 -which=true -path="by.out"
real 0m0.027s
user 0m0.017s
sys 0m0.012s
banjakukutekiiMac:shell panshiqu$ time ./gomd5 -cnt=1 -which=true -path="by2.out"
real 0m0.048s
user 0m0.033s
sys 0m0.018s
banjakukutekiiMac:shell panshiqu$ time ./gomd5 -cnt=1 -which=false -path="by.out"
real 0m0.018s
user 0m0.012s
sys 0m0.004s
banjakukutekiiMac:shell panshiqu$ time ./gomd5 -cnt=1 -which=false -path="by2.out"
real 0m0.031s
user 0m0.024s
sys 0m0.005s
banjakukutekiiMac:shell panshiqu$ time md5 by.out
MD5 (by.out) = 9d79e19a00cef1ae1bb6518ca4adf9de
real 0m0.023s
user 0m0.019s
sys 0m0.006s
banjakukutekiiMac:shell panshiqu$ time md5 by2.out
MD5 (by2.out) = 0a029a460a20e8dcb00d032d6fab74c6
real 0m0.042s
user 0m0.037s
sys 0m0.009s
总结:
* 不管什么方法都会随着文件变大时间会变长,上面的例子大约都是2倍
* io.Copy
方法效率最高,建议大家这样使用