You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
1.6 KiB

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