...

Source file src/github.com/patrickmn/go-cache/sharded_test.go

Documentation: github.com/patrickmn/go-cache

     1  package cache
     2  
     3  import (
     4  	"strconv"
     5  	"sync"
     6  	"testing"
     7  	"time"
     8  )
     9  
    10  // func TestDjb33(t *testing.T) {
    11  // }
    12  
    13  var shardedKeys = []string{
    14  	"f",
    15  	"fo",
    16  	"foo",
    17  	"barf",
    18  	"barfo",
    19  	"foobar",
    20  	"bazbarf",
    21  	"bazbarfo",
    22  	"bazbarfoo",
    23  	"foobarbazq",
    24  	"foobarbazqu",
    25  	"foobarbazquu",
    26  	"foobarbazquux",
    27  }
    28  
    29  func TestShardedCache(t *testing.T) {
    30  	tc := unexportedNewSharded(DefaultExpiration, 0, 13)
    31  	for _, v := range shardedKeys {
    32  		tc.Set(v, "value", DefaultExpiration)
    33  	}
    34  }
    35  
    36  func BenchmarkShardedCacheGetExpiring(b *testing.B) {
    37  	benchmarkShardedCacheGet(b, 5*time.Minute)
    38  }
    39  
    40  func BenchmarkShardedCacheGetNotExpiring(b *testing.B) {
    41  	benchmarkShardedCacheGet(b, NoExpiration)
    42  }
    43  
    44  func benchmarkShardedCacheGet(b *testing.B, exp time.Duration) {
    45  	b.StopTimer()
    46  	tc := unexportedNewSharded(exp, 0, 10)
    47  	tc.Set("foobarba", "zquux", DefaultExpiration)
    48  	b.StartTimer()
    49  	for i := 0; i < b.N; i++ {
    50  		tc.Get("foobarba")
    51  	}
    52  }
    53  
    54  func BenchmarkShardedCacheGetManyConcurrentExpiring(b *testing.B) {
    55  	benchmarkShardedCacheGetManyConcurrent(b, 5*time.Minute)
    56  }
    57  
    58  func BenchmarkShardedCacheGetManyConcurrentNotExpiring(b *testing.B) {
    59  	benchmarkShardedCacheGetManyConcurrent(b, NoExpiration)
    60  }
    61  
    62  func benchmarkShardedCacheGetManyConcurrent(b *testing.B, exp time.Duration) {
    63  	b.StopTimer()
    64  	n := 10000
    65  	tsc := unexportedNewSharded(exp, 0, 20)
    66  	keys := make([]string, n)
    67  	for i := 0; i < n; i++ {
    68  		k := "foo" + strconv.Itoa(n)
    69  		keys[i] = k
    70  		tsc.Set(k, "bar", DefaultExpiration)
    71  	}
    72  	each := b.N / n
    73  	wg := new(sync.WaitGroup)
    74  	wg.Add(n)
    75  	for _, v := range keys {
    76  		go func() {
    77  			for j := 0; j < each; j++ {
    78  				tsc.Get(v)
    79  			}
    80  			wg.Done()
    81  		}()
    82  	}
    83  	b.StartTimer()
    84  	wg.Wait()
    85  }
    86  

View as plain text