Skip to content

Commit

Permalink
Benchmark for cipher init.
Browse files Browse the repository at this point in the history
  • Loading branch information
cyfdecyf committed May 26, 2013
1 parent 28b2a41 commit a0e180b
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 1 deletion.
12 changes: 11 additions & 1 deletion shadowsocks/encrypt.go
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ type cipherInfo struct {
// instead of cipher.Block, so we need to have the following adapter
// functions.
// The specific cipher types makes it possible to use Copy to optimize cipher
// initialization, but do this AFTER evaluation.
// initialization.

func newBlowFishCipher(key []byte) (cipher.Block, error) {
return blowfish.NewCipher(key)
Expand Down Expand Up @@ -200,6 +200,16 @@ func (c *Cipher) Copy() *Cipher {
// This optimization maybe not necessary. But without this function, we
// need to maintain a table cache for newTableCipher and use lock to
// protect concurrent access to that cache.

// AES and DES ciphers does not return specific types, so it's difficult
// to create copy. But their initizliation time is less than 4000ns on my
// 2.26 GHz Intel Core 2 Duo processor. So no need to worry.

// Currently, blow-fish and cast5 initialization cost is an order of
// maganitude slower than other ciphers. (I'm not sure whether this is
// because the current implementation is not highly optimized, or this is
// the nature of the algorithm.)

switch c.enc.(type) {
case tableCipher:
return c
Expand Down
52 changes: 52 additions & 0 deletions shadowsocks/encrypt_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,55 @@ func TestAES256(t *testing.T) {
func TestDES(t *testing.T) {
testBlockCipher(t, "des-cfb")
}

var cipherKey = make([]byte, 64)

func init() {
for i := 0; i < len(cipherKey); i++ {
cipherKey[i] = byte(i)
}
}

func BenchmarkRC4Init(b *testing.B) {
key := cipherKey[:16]
for i := 0; i < b.N; i++ {
rc4.NewCipher(key)
}
}

func benchmarkCipherInit(b *testing.B, ci *cipherInfo) {
key := cipherKey[:ci.keyLen]
for i := 0; i < b.N; i++ {
ci.newBlock(key)
}
}

func BenchmarkAES128Init(b *testing.B) {
ci := cipherMethod["aes-128-cfb"]
benchmarkCipherInit(b, &ci)
}

func BenchmarkAES192Init(b *testing.B) {
ci := cipherMethod["aes-192-cfb"]
benchmarkCipherInit(b, &ci)
}

func BenchmarkAES256Init(b *testing.B) {
ci := cipherMethod["aes-256-cfb"]
benchmarkCipherInit(b, &ci)
}

func BenchmarkBlowFishInit(b *testing.B) {
ci := cipherMethod["bf-cfb"]
benchmarkCipherInit(b, &ci)
}

func BenchmarkCast5Init(b *testing.B) {
ci := cipherMethod["bf-cfb"]
benchmarkCipherInit(b, &ci)
}

func BenchmarkDESInit(b *testing.B) {
ci := cipherMethod["des-cfb"]
benchmarkCipherInit(b, &ci)
}

0 comments on commit a0e180b

Please sign in to comment.