Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 21 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Fixed-capacity in-memory caches for Go.
- **Batch lookups.** `GetMany` loads up to 32 entries from memory in parallel.
- **Evictions handed back.** `Set` returns the entry it replaced or evicted.
- **Statistics.** `stats.Wrap` counts hits, misses and evictions.
- **Expiry.** `expire.Wrap` gives entries a time to live.
- **Safe for concurrent use**, and depends only on the standard library.

## Install
Expand Down Expand Up @@ -80,6 +81,20 @@ fmt.Println(s.HitRatio(), s.Evictions, s.Len, s.Cap)
The counts only go up; `s.Sub(prev)` gives those of an interval. A `Get` that hits took
10–14% longer through the wrapper (`tinylfu`, Apple M3 Max).

### Expiry

```go
cache := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute)

cache.Set("a", 1) // Expires in a minute,
cache.SetWithTTL("b", 2, 10*time.Second) // and this one in ten seconds.
```

An expired entry is a miss, but takes up room until it is evicted, set again, deleted or
cleared, and reads of it still count with the policy. Reads look at a copy of the time that a
timer updates every 10 ms, and at the time itself near a deadline. A `Get` that hits took
11–15% longer through the wrapper, and a `Set` 17 ns longer (`tinylfu`, Apple M3 Max).

## Benchmarks

<p>
Expand Down Expand Up @@ -151,9 +166,12 @@ own.

## What it does not do

No expiry, no weights or sizes in bytes, no loading functions. If you need those, or if many
CPUs overwrite a tenth to a quarter of what they read, use
[otter](https://github.com/maypok86/otter).
- **No sizes in bytes or weights.** Capacity counts entries; set it from a typical entry size.
- **No loader** that fetches a missing key once for all the callers that ask for it.
- **No cleanup of expired entries**; see [Expiry](#expiry).
- **Overwrites do not scale with CPUs**; otter's do ([Benchmarks](#benchmarks)).

For any of these, use [otter](https://github.com/maypok86/otter).

## License

Expand Down
5 changes: 3 additions & 2 deletions evict.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,14 +43,15 @@
//
// This package holds what the caches have in common: the [Cache] interface.
// [github.com/floatdrop/evict/stats] counts the hits, misses and evictions of
// any of them.
// any of them, and [github.com/floatdrop/evict/expire] gives their entries a
// time to live.
package evict

import "iter"

// Cache is the behaviour common to every cache in this module. It is
// implemented by *lru.Cache, *twoq.Cache, *sieve.Cache, *s3fifo.Cache and
// *tinylfu.Cache.
// *tinylfu.Cache, and by the wrappers *stats.Cache and *expire.Cache.
//
// All methods are safe for concurrent use.
type Cache[K comparable, V any] interface {
Expand Down
166 changes: 166 additions & 0 deletions expire/bench_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,166 @@
package expire_test

import (
"fmt"
"math/rand/v2"
"sync"
"testing"
"time"

"github.com/floatdrop/evict"
"github.com/floatdrop/evict/expire"
"github.com/floatdrop/evict/internal/cachetest"
"github.com/floatdrop/evict/s3fifo"
"github.com/floatdrop/evict/tinylfu"
)

const benchCapacity = 1 << 14

// fill sets the keys 0 to benchCapacity-1, through set.
func fill(set func(key, value int)) {
for key := range benchCapacity {
set(key, key)
}
}

// benchGet reads entries that are all there, on every CPU at once. The loop is
// written out for each type, so that it makes the call it is about and no
// other.
func BenchmarkGet(b *testing.B) {
b.Run("direct", func(b *testing.B) {
c := tinylfu.New[int, int](benchCapacity)
fill(func(k, v int) { c.Set(k, v) })
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
i := rand.Int()
for pb.Next() {
c.Get(i & (benchCapacity - 1))
i++
}
})
})

b.Run("interface", func(b *testing.B) {
var c evict.Cache[int, int] = tinylfu.New[int, int](benchCapacity)
fill(func(k, v int) { c.Set(k, v) })
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
i := rand.Int()
for pb.Next() {
c.Get(i & (benchCapacity - 1))
i++
}
})
})

b.Run("expire", func(b *testing.B) {
c := expire.Wrap(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour)
fill(func(k, v int) { c.Set(k, v) })
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
i := rand.Int()
for pb.Next() {
c.Get(i & (benchCapacity - 1))
i++
}
})
})

// Every entry is due within 50 ms of the copy of the time, so every
// read reads the time itself.
b.Run("due", func(b *testing.B) {
clock := expire.NewRealClock()
c := expire.WrapWith(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour, clock)
fill(func(k, v int) { c.Set(k, v) })
clock.SetCopy(clock.Read() + time.Hour - 30*time.Millisecond)
// Filling the cache takes about a millisecond. Had it taken 30, the
// first entries would have expired by the copy of the time.
for _, key := range []int{0, benchCapacity - 1} {
if _, ok := c.Get(key); !ok {
b.Fatalf("Get(%d) misses; the benchmark is for entries that are due", key)
}
}
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
i := rand.Int()
for pb.Next() {
c.Get(i & (benchCapacity - 1))
i++
}
})
})
}

// BenchmarkSet replaces entries, on one CPU at a time: Set takes the lock of a
// shard either way, and reads the time through the wrapper.
func BenchmarkSet(b *testing.B) {
b.Run("direct", func(b *testing.B) {
c := tinylfu.New[int, int](benchCapacity)
fill(func(k, v int) { c.Set(k, v) })
b.ReportAllocs()
i := 0
for b.Loop() {
c.Set(i&(benchCapacity-1), i)
i++
}
})

b.Run("expire", func(b *testing.B) {
c := expire.Wrap(tinylfu.New[int, expire.Entry[int]](benchCapacity), time.Hour)
fill(func(k, v int) { c.Set(k, v) })
b.ReportAllocs()
i := 0
for b.Loop() {
c.Set(i&(benchCapacity-1), i)
i++
}
})
}

// BenchmarkGetMany looks up keys of a cache too large for the CPU's caches, on
// every CPU at once: with the GetMany of s3fifo, and with that of the wrapper,
// which looks them up in batches of its own. ns/key is the time per key.
func BenchmarkGetMany(b *testing.B) {
const entries = 1 << 20
keys, seq := cachetest.UniformInts(entries)

run := func(b *testing.B, n int, getMany func(keys, values []int, found []bool)) {
b.Helper()
mask := len(seq) - 1
var (
mu sync.Mutex
hits int
)
b.ReportAllocs()
b.RunParallel(func(pb *testing.PB) {
values, found := make([]int, n), make([]bool, n)
i, h := rand.Int()&^(n-1), 0
for pb.Next() {
getMany(seq[i&mask:i&mask+n], values, found)
for _, ok := range found {
if ok {
h++
}
}
i += n
}
mu.Lock()
hits += h
mu.Unlock()
})
total := float64(b.N * n)
b.ReportMetric(float64(b.Elapsed().Nanoseconds())/total, "ns/key")
b.ReportMetric(float64(hits)/total, "hits")
}

direct := s3fifo.New[int, int](entries)
wrapped := expire.Wrap(s3fifo.New[int, expire.Entry[int]](entries), time.Hour)
for _, k := range keys {
direct.Set(k, k)
wrapped.Set(k, k)
}
for _, n := range []int{8, 32, 128} {
b.Run(fmt.Sprintf("keys=%d/direct", n), func(b *testing.B) { run(b, n, direct.GetMany) })
b.Run(fmt.Sprintf("keys=%d/expire", n), func(b *testing.B) { run(b, n, wrapped.GetMany) })
}
}
49 changes: 49 additions & 0 deletions expire/example_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
package expire_test

import (
"fmt"
"time"

"github.com/floatdrop/evict/expire"
"github.com/floatdrop/evict/stats"
"github.com/floatdrop/evict/tinylfu"
)

func Example() {
// The cache holds expire.Entry values, which are the values with the
// time at which they expire.
cache := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute)

cache.Set("a", 1) // Expires in a minute,
cache.SetWithTTL("b", 2, time.Hour) // this one in an hour,
cache.SetWithTTL("c", 3, 0) // and this one already has.

for _, key := range []string{"a", "b", "c"} {
value, ok := cache.Get(key)
fmt.Println(key, value, ok)
}

// Output:
// a 1 true
// b 2 true
// c 0 false
}

// Wrapped in stats, a cache counts a key whose entry has expired as a miss.
func Example_stats() {
expiring := expire.Wrap(tinylfu.New[string, expire.Entry[int]](10_000), time.Minute)
cache := stats.Wrap(expiring)

cache.Set("a", 1)
cache.Set("b", 2)
expiring.SetWithTTL("b", 3, 0) // Its time is up.

cache.Get("a")
cache.Get("b")

s := cache.Stats()
fmt.Println(s.Hits, "hit,", s.Misses, "miss")

// Output:
// 1 hit, 1 miss
}
Loading