我需要為超過 1GB 的文件計(jì)算 sha256 校驗(yàn)和(按塊讀取文件),目前我正在使用 python:import hashlibimport timestart_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認(rèn)為我可以獲得更快的結(jié)果,但是在嘗試以下代碼后,它運(yùn)行慢了幾秒鐘:package mainimport ( "crypto/sha256" "fmt" "io" "math" "os" "time") const fileChunk = 8192func 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)}如果可能,知道如何改進(jìn)golang代碼嗎?也許使用所有計(jì)算機(jī) CPU 內(nèi)核,一個(gè)用于讀取,另一個(gè)用于散列,有什么想法嗎?
- 2 回答
- 0 關(guān)注
- 218 瀏覽
添加回答
舉報(bào)
0/150
提交
取消