Created
June 8, 2021 09:52
-
-
Save ken39arg/92f5a505d72b9995d399d78ab5d74d80 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"context" | |
"crypto/sha1" | |
"encoding/hex" | |
"fmt" | |
"hash/crc32" | |
"log" | |
"math/rand" | |
"os" | |
"testing" | |
"time" | |
"github.com/go-redis/redis/v8" | |
) | |
var cli redis.UniversalClient | |
func init() { | |
cli = redis.NewClient(&redis.Options{ | |
Addr: os.Getenv("REDIS_ADDRESS"), | |
}) | |
rand.Seed(time.Now().UnixNano()) | |
} | |
func set(key string) { | |
if err := cli.Set(context.Background(), key, 123, time.Second).Err(); err != nil { | |
log.Printf("set err: %s", err) | |
} | |
} | |
func get(key string) { | |
if _, err := cli.Get(context.Background(), key).Int(); err != nil && err != redis.Nil { | |
log.Printf("get err: %s", err) | |
} | |
} | |
const letterBytes = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" | |
var letterSize = len(letterBytes) | |
var sizes = []int{32, 64, 128, 256, 512, 1024, 2048, 4096, 8192} | |
func genkey(size int) string { | |
r := make([]byte, size/2) | |
rand.Read(r) | |
return hex.EncodeToString(r) | |
} | |
func TestGenKey(t *testing.T) { | |
for _, size := range sizes { | |
key := genkey(size) | |
if len(key) != size { | |
t.Errorf("key size is differ") | |
} | |
} | |
} | |
func Benchmark_keygenenrate(b *testing.B) { | |
for _, size := range sizes { | |
b.Run(fmt.Sprintf("%04d", size), func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
genkey(size) | |
} | |
}) | |
} | |
} | |
func benchMark(b *testing.B, keyfilter func(string) string) { | |
log.Printf("generated: %s", keyfilter(genkey(128))) | |
for _, size := range sizes { | |
b.ResetTimer() | |
b.Run(fmt.Sprintf("%04d", size), func(b *testing.B) { | |
for i := 0; i < b.N; i++ { | |
key := genkey(size) | |
get(keyfilter(key)) | |
set(keyfilter(key)) | |
get(keyfilter(key)) | |
} | |
}) | |
} | |
} | |
func Benchmark_RedisKey_Raw(b *testing.B) { | |
benchMark(b, func(s string) string { return s }) | |
} | |
func Benchmark_RedisKey_SHA1(b *testing.B) { | |
benchMark(b, func(s string) string { | |
h := sha1.New() | |
h.Write([]byte(s)) | |
return hex.EncodeToString(h.Sum(nil)) | |
}) | |
} | |
func Benchmark_RedisKey_CRC32(b *testing.B) { | |
benchMark(b, func(s string) string { | |
h := crc32.NewIEEE() | |
h.Write([]byte(s)) | |
return hex.EncodeToString(h.Sum(nil)) | |
}) | |
} |
Author
ken39arg
commented
Jun 9, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment