faster random strings

This commit is contained in:
Jae Kwon 2014-05-28 01:00:05 -07:00
parent 9579a653c7
commit 60004db2ad
2 changed files with 20 additions and 18 deletions

View File

@ -154,7 +154,7 @@ func TestIntegration(t *testing.T) {
var updated bool
randomRecord := func() *record {
return &record{ RandStr(20), RandStr(20) }
return &record{ randstr(20), randstr(20) }
}
for i := range records {
@ -179,7 +179,7 @@ func TestIntegration(t *testing.T) {
if has := tree.Has(r.key); !has {
t.Error("Missing key", r.key)
}
if has := tree.Has(RandStr(12)); has {
if has := tree.Has(randstr(12)); has {
t.Error("Table has extra key")
}
if val := tree.Get(r.key); !(val.(String)).Equals(r.value) {
@ -197,7 +197,7 @@ func TestIntegration(t *testing.T) {
if has := tree.Has(r.key); !has {
t.Error("Missing key", r.key)
}
if has := tree.Has(RandStr(12)); has {
if has := tree.Has(randstr(12)); has {
t.Error("Table has extra key")
}
if val := tree.Get(r.key); !(val.(String)).Equals(r.value) {
@ -216,7 +216,7 @@ func TestPersistence(t *testing.T) {
// Create some random key value pairs
records := make(map[String]String)
for i:=0; i<10000; i++ {
records[String(RandStr(20))] = String(RandStr(20))
records[String(randstr(20))] = String(randstr(20))
}
// Construct some tree and save it
@ -241,7 +241,7 @@ func TestPersistence(t *testing.T) {
func BenchmarkHash(b *testing.B) {
b.StopTimer()
s := RandStr(128)
s := randstr(128)
b.StartTimer()
for i := 0; i < b.N; i++ {
@ -260,7 +260,7 @@ func BenchmarkImmutableAvlTree(b *testing.B) {
}
randomRecord := func() *record {
return &record{ RandStr(32), RandStr(32) }
return &record{ randstr(32), randstr(32) }
}
t := NewIAVLTree(nil)
@ -269,6 +269,8 @@ func BenchmarkImmutableAvlTree(b *testing.B) {
t.Put(r.key, r.value)
}
fmt.Println("ok, starting")
b.StartTimer()
for i := 0; i < b.N; i++ {
r := randomRecord()

View File

@ -1,8 +1,7 @@
package merkle
import (
"math/big"
"crypto/rand"
"os"
"fmt"
)
@ -32,17 +31,18 @@ func printIAVLNode(node *IAVLNode, indent int) {
}
const allRandChars = "0123456789"
func RandStr(numChars int) String {
var res string
for i:=0; i<numChars; i++ {
v, err := rand.Int(rand.Reader, big.NewInt(int64(10)))
if err != nil { panic(err) }
randIndex := int(v.Int64())
res = res + allRandChars[randIndex:randIndex+1]
func randstr(length int) String {
if urandom, err := os.Open("/dev/urandom"); err != nil {
panic(err)
} else {
slice := make([]byte, length)
if _, err := urandom.Read(slice); err != nil {
panic(err)
}
urandom.Close()
return String(slice)
}
return String(res)
panic("unreachable")
}
func maxUint8(a, b uint8) uint8 {