github.com/angenalZZZ/gofunc@v0.0.0-20210507121333-48ff1be3917b/data/cache/fastcache/file_timing_test.go (about)

     1  package fastcache
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  	"sync"
     7  	"testing"
     8  )
     9  
    10  func BenchmarkSaveToFile(b *testing.B) {
    11  	for _, concurrency := range []int{1, 2, 4, 8, 16} {
    12  		b.Run(fmt.Sprintf("concurrency_%d", concurrency), func(b *testing.B) {
    13  			benchmarkSaveToFile(b, concurrency)
    14  		})
    15  	}
    16  }
    17  
    18  func benchmarkSaveToFile(b *testing.B, concurrency int) {
    19  	filePath := fmt.Sprintf("BencharkSaveToFile.%d.fastcache", concurrency)
    20  	defer os.RemoveAll(filePath)
    21  	c := newBenchCache()
    22  
    23  	b.ReportAllocs()
    24  	b.ResetTimer()
    25  	b.SetBytes(benchCacheSize)
    26  	for i := 0; i < b.N; i++ {
    27  		if err := c.SaveToFileConcurrent(filePath, concurrency); err != nil {
    28  			b.Fatalf("unexpected error when saving to file: %s", err)
    29  		}
    30  	}
    31  }
    32  
    33  func BenchmarkLoadFromFile(b *testing.B) {
    34  	for _, concurrency := range []int{1, 2, 4, 8, 16} {
    35  		b.Run(fmt.Sprintf("concurrency_%d", concurrency), func(b *testing.B) {
    36  			benchmarkLoadFromFile(b, concurrency)
    37  		})
    38  	}
    39  }
    40  
    41  func benchmarkLoadFromFile(b *testing.B, concurrency int) {
    42  	filePath := fmt.Sprintf("BenchmarkLoadFromFile.%d.fastcache", concurrency)
    43  	defer os.RemoveAll(filePath)
    44  
    45  	c := newBenchCache()
    46  	if err := c.SaveToFileConcurrent(filePath, concurrency); err != nil {
    47  		b.Fatalf("cannot save cache to file: %s", err)
    48  	}
    49  
    50  	b.ReportAllocs()
    51  	b.ResetTimer()
    52  	b.SetBytes(benchCacheSize)
    53  	for i := 0; i < b.N; i++ {
    54  		c, err := LoadFromFile(filePath)
    55  		if err != nil {
    56  			b.Fatalf("cannot load cache from file: %s", err)
    57  		}
    58  		var s Stats
    59  		c.UpdateStats(&s)
    60  		if s.EntriesCount == 0 {
    61  			b.Fatalf("unexpected zero entries")
    62  		}
    63  	}
    64  }
    65  
    66  var (
    67  	benchCache     *Cache
    68  	benchCacheOnce sync.Once
    69  )
    70  
    71  func newBenchCache() *Cache {
    72  	benchCacheOnce.Do(func() {
    73  		c := New(benchCacheSize)
    74  		itemsCount := benchCacheSize / 20
    75  		for i := 0; i < itemsCount; i++ {
    76  			k := []byte(fmt.Sprintf("key %d", i))
    77  			v := []byte(fmt.Sprintf("value %d", i))
    78  			c.Set(k, v)
    79  		}
    80  		benchCache = c
    81  	})
    82  	return benchCache
    83  }
    84  
    85  const benchCacheSize = bucketsCount * chunkSize