github.com/tendermint/tmlibs@v0.9.0/db/go_level_db_test.go (about)

     1  package db
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/binary"
     6  	"fmt"
     7  	"testing"
     8  
     9  	cmn "github.com/tendermint/tmlibs/common"
    10  )
    11  
    12  func BenchmarkRandomReadsWrites(b *testing.B) {
    13  	b.StopTimer()
    14  
    15  	numItems := int64(1000000)
    16  	internal := map[int64]int64{}
    17  	for i := 0; i < int(numItems); i++ {
    18  		internal[int64(i)] = int64(0)
    19  	}
    20  	db, err := NewGoLevelDB(cmn.Fmt("test_%x", cmn.RandStr(12)), "")
    21  	if err != nil {
    22  		b.Fatal(err.Error())
    23  		return
    24  	}
    25  
    26  	fmt.Println("ok, starting")
    27  	b.StartTimer()
    28  
    29  	for i := 0; i < b.N; i++ {
    30  		// Write something
    31  		{
    32  			idx := (int64(cmn.RandInt()) % numItems)
    33  			internal[idx]++
    34  			val := internal[idx]
    35  			idxBytes := int642Bytes(int64(idx))
    36  			valBytes := int642Bytes(int64(val))
    37  			//fmt.Printf("Set %X -> %X\n", idxBytes, valBytes)
    38  			db.Set(
    39  				idxBytes,
    40  				valBytes,
    41  			)
    42  		}
    43  		// Read something
    44  		{
    45  			idx := (int64(cmn.RandInt()) % numItems)
    46  			val := internal[idx]
    47  			idxBytes := int642Bytes(int64(idx))
    48  			valBytes := db.Get(idxBytes)
    49  			//fmt.Printf("Get %X -> %X\n", idxBytes, valBytes)
    50  			if val == 0 {
    51  				if !bytes.Equal(valBytes, nil) {
    52  					b.Errorf("Expected %v for %v, got %X",
    53  						nil, idx, valBytes)
    54  					break
    55  				}
    56  			} else {
    57  				if len(valBytes) != 8 {
    58  					b.Errorf("Expected length 8 for %v, got %X",
    59  						idx, valBytes)
    60  					break
    61  				}
    62  				valGot := bytes2Int64(valBytes)
    63  				if val != valGot {
    64  					b.Errorf("Expected %v for %v, got %v",
    65  						val, idx, valGot)
    66  					break
    67  				}
    68  			}
    69  		}
    70  	}
    71  
    72  	db.Close()
    73  }
    74  
    75  func int642Bytes(i int64) []byte {
    76  	buf := make([]byte, 8)
    77  	binary.BigEndian.PutUint64(buf, uint64(i))
    78  	return buf
    79  }
    80  
    81  func bytes2Int64(buf []byte) int64 {
    82  	return int64(binary.BigEndian.Uint64(buf))
    83  }