@
lniwn #9
```
package main
import (
"encoding/binary"
"fmt"
"log"
"math/rand"
"os"
"time"
"
go.etcd.io/bbolt"
)
func itob(v int) []byte {
b := make([]byte, 8)
binary.BigEndian.PutUint64(b, uint64(v))
return b
}
func main() {
test2()
}
// 测试随机批量连续
func test2() {
os.Remove("test2.db")
db, err := bbolt.Open("test2.db", 0600, nil)
if err != nil {
log.Fatal(err)
}
defer db.Close()
err = db.Update(func(tx *bbolt.Tx) error {
_, err := tx.CreateBucketIfNotExists([]byte("MyBucket"))
return err
})
if err != nil {
panic(err)
}
buf := []byte("0000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000")
data := make([]int, 100000)
for i, _ := range data {
data[i] =
rand.Int()
}
for i := 0; i < 20; i++ {
sTime := time.Now()
err = db.Update(func(tx *bbolt.Tx) error {
b := tx.Bucket([]byte("MyBucket"))
for _, v := range data {
err := b.Put(itob(v), buf)
if err != nil {
return err
}
}
return nil
})
/*
乱序批量写 100000:15.2067849s
乱序批量写 100000:409.6209ms
乱序批量写 100000:421.3134ms
乱序批量写 100000:381.5371ms
乱序批量写 100000:381.5839ms
乱序批量写 100000:361.8394ms
乱序批量写 100000:362.8142ms
乱序批量写 100000:364.7673ms
乱序批量写 100000:359.8283ms
乱序批量写 100000:376.0383ms
乱序批量写 100000:361.9876ms
乱序批量写 100000:362.0323ms
乱序批量写 100000:374.0311ms
乱序批量写 100000:365.0348ms
乱序批量写 100000:360.0383ms
乱序批量写 100000:361.022ms
乱序批量写 100000:364.0195ms
乱序批量写 100000:354.024ms
乱序批量写 100000:370.0098ms
乱序批量写 100000:379.9845ms
*/
fmt.Println("乱序批量写 100000:", time.Now().Sub(sTime))
}
}
```