【发布时间】:2015-01-15 14:19:01
【问题描述】:
我需要为超过 1GB 的文件计算 sha256 校验和(按块读取文件),目前我正在使用 python:
import hashlib
import time
start_time = time.time()
def sha256sum(filename="big.txt", block_size=2 ** 13):
sha = hashlib.sha256()
with open(filename, 'rb') as f:
for chunk in iter(lambda: f.read(block_size), b''):
sha.update(chunk)
return sha.hexdigest()
input_file = '/tmp/1GB.raw'
print 'checksum is: %s\n' % sha256sum(input_file)
print 'Elapsed time: %s' % str(time.time() - start_time)
我想尝试一下golang,以为我可以得到更快的结果,但是在尝试了以下代码后,它的运行速度慢了几秒钟:
package main
import (
"crypto/sha256"
"fmt"
"io"
"math"
"os"
"time"
)
const fileChunk = 8192
func File(file string) string {
fh, err := os.Open(file)
if err != nil {
panic(err.Error())
}
defer fh.Close()
stat, _ := fh.Stat()
size := stat.Size()
chunks := uint64(math.Ceil(float64(size) / float64(fileChunk)))
h := sha256.New()
for i := uint64(0); i < chunks; i++ {
csize := int(math.Min(fileChunk, float64(size-int64(i*fileChunk))))
buf := make([]byte, csize)
fh.Read(buf)
io.WriteString(h, string(buf))
}
return fmt.Sprintf("%x", h.Sum(nil))
}
func main() {
start := time.Now()
fmt.Printf("checksum is: %s\n", File("/tmp/1G.raw"))
elapsed := time.Since(start)
fmt.Printf("Elapsed time: %s\n", elapsed)
}
如果可能的话,知道如何改进golang 代码吗?也许要使用所有计算机 CPU 内核,一个用于读取,另一个用于散列,有什么想法吗?
更新
按照建议,我正在使用此代码:
package main
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"io"
"os"
"time"
)
func main() {
start := time.Now()
fh, err := os.Open("/tmp/1GB.raw")
if err != nil {
panic(err.Error())
}
defer fh.Close()
h := sha256.New()
_, err = io.Copy(h, fh)
if err != nil {
panic(err.Error())
}
fmt.Println(hex.EncodeToString(h.Sum(nil)))
fmt.Printf("Elapsed time: %s\n", time.Since(start))
}
为了测试,我正在创建 1GB 文件:
# mkfile 1G /tmp/1GB.raw
新版本速度更快但没那么多,那使用频道呢?使用多个 CPU/内核是否有助于改进?我期望至少有 20% 的改进,但不幸的是,我几乎没有获得任何收益,几乎什么都没有。
python的时间结果
5.867u 0.250s 0:06.15 99.3% 0+0k 0+0io 0pf+0w
编译(go build)并执行二进制后go的时间结果:
5.687u 0.198s 0:05.93 98.9% 0+0k 0+0io 0pf+0w
还有什么想法吗?
测试结果
使用下面@icza 接受的答案上发布的频道的版本
Elapsed time: 5.894779733s
使用no频道的版本:
Elapsed time: 5.823489239s
我以为使用频道会增加一点,但似乎没有。
我在 MacBook Pro OS X Yosemite 上运行它。使用 go 版本:
go version go1.4.1 darwin/amd64
更新 2
将 runtime.GOMAXPROCS 设置为 4:
runtime.GOMAXPROCS(4)
让事情变得更快:
Elapsed time: 5.741511748s
更新 3
将块大小更改为 8192(如在 python 版本中)给出预期结果:
...
for b, hasMore := make([]byte, 8192<<10), true; hasMore; {
...
同样只使用 runtime.GOMAXPROCS(2)
【问题讨论】:
-
无论如何,我不希望它会[多]快。大部分工作是在 IO 层或哈希层(由其他人高效编写,用 C 语言为 Python)完成的:这并不是真正的“Python 代码”与“Go 代码”。
-
你能解释一下测试结果吗?数字/时间是什么意思?
-
是output of the time命令,基本上我用time ./checksum或者time python checksum.py
-
您是否尝试过使用并非全为零的文件顺便说一句?
-
另外,我已经用其他几个哈希函数运行了代码,sha512 快两倍,md5 x5 快,sha1 快 x3。
标签: performance go checksum