From: Ilya Tocar Date: Wed, 9 Aug 2017 18:21:20 +0000 (-0500) Subject: crypto/sha1: speed up sha1 for very small blocks X-Git-Tag: go1.10beta1~1136 X-Git-Url: http://www.git.cypherpunks.su/?a=commitdiff_plain;h=dc3b8a193cfa3f9ab9664ee58700e60761fb2f84;p=gostls13.git crypto/sha1: speed up sha1 for very small blocks For very small blocks significant time is spent in checkSum function, adding necessary padding. Instead of writing it byte by byte, copy encoding/binary PutUint functions, which are compiled into single mov. name old time/op new time/op delta Hash8Bytes-6 344ns ± 0% 310ns ± 0% -9.78% (p=0.000 n=10+9) Hash320Bytes-6 1.28µs ± 0% 1.25µs ± 0% -2.58% (p=0.000 n=10+10) Hash1K-6 2.51µs ± 0% 2.47µs ± 0% -1.67% (p=0.000 n=10+10) Hash8K-6 15.8µs ± 0% 15.7µs ± 1% -0.21% (p=0.023 n=10+10) name old speed new speed delta Hash8Bytes-6 23.2MB/s ± 0% 25.7MB/s ± 0% +10.77% (p=0.000 n=10+9) Hash320Bytes-6 249MB/s ± 0% 256MB/s ± 0% +2.65% (p=0.000 n=10+10) Hash1K-6 408MB/s ± 0% 414MB/s ± 0% +1.70% (p=0.000 n=10+10) Change-Id: I3975ee929465c7dd137d0ca757ad3792a004e1a3 Reviewed-on: https://go-review.googlesource.com/54391 Run-TryBot: Ilya Tocar TryBot-Result: Gobot Gobot Reviewed-by: Giovanni Bajo Reviewed-by: Filippo Valsorda --- diff --git a/src/crypto/sha1/sha1.go b/src/crypto/sha1/sha1.go index 6b1721470b..0e65015e2f 100644 --- a/src/crypto/sha1/sha1.go +++ b/src/crypto/sha1/sha1.go @@ -104,9 +104,7 @@ func (d *digest) checkSum() [Size]byte { // Length in bits. len <<= 3 - for i := uint(0); i < 8; i++ { - tmp[i] = byte(len >> (56 - 8*i)) - } + putUint64(tmp[:], len) d.Write(tmp[0:8]) if d.nx != 0 { @@ -114,12 +112,12 @@ func (d *digest) checkSum() [Size]byte { } var digest [Size]byte - for i, s := range d.h { - digest[i*4] = byte(s >> 24) - digest[i*4+1] = byte(s >> 16) - digest[i*4+2] = byte(s >> 8) - digest[i*4+3] = byte(s) - } + + putUint32(digest[0:], d.h[0]) + putUint32(digest[4:], d.h[1]) + putUint32(digest[8:], d.h[2]) + putUint32(digest[12:], d.h[3]) + putUint32(digest[16:], d.h[4]) return digest } @@ -199,3 +197,23 @@ func Sum(data []byte) [Size]byte { d.Write(data) return d.checkSum() } + +func putUint64(x []byte, s uint64) { + _ = x[7] + x[0] = byte(s >> 56) + x[1] = byte(s >> 48) + x[2] = byte(s >> 40) + x[3] = byte(s >> 32) + x[4] = byte(s >> 24) + x[5] = byte(s >> 16) + x[6] = byte(s >> 8) + x[7] = byte(s) +} + +func putUint32(x []byte, s uint32) { + _ = x[3] + x[0] = byte(s >> 24) + x[1] = byte(s >> 16) + x[2] = byte(s >> 8) + x[3] = byte(s) +}