github.com/xgzlucario/GigaCache@v0.0.0-20240508025442-54204e9c8a6b/benchmark/main.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"runtime"
     7  	"runtime/debug"
     8  	"time"
     9  
    10  	cache "github.com/xgzlucario/GigaCache"
    11  )
    12  
    13  var previousPause time.Duration
    14  
    15  func gcPause() time.Duration {
    16  	runtime.GC()
    17  	var stats debug.GCStats
    18  	debug.ReadGCStats(&stats)
    19  	pause := stats.PauseTotal - previousPause
    20  	previousPause = stats.PauseTotal
    21  	return pause
    22  }
    23  
    24  func genKV(id int) (string, []byte) {
    25  	k := fmt.Sprintf("%08x", id)
    26  	return k, []byte(k)
    27  }
    28  
    29  func main() {
    30  	c := ""
    31  	entries := 0
    32  	flag.StringVar(&c, "cache", "cache", "cache to bench.")
    33  	flag.IntVar(&entries, "entries", 2000*10000, "number of entries to test.")
    34  	flag.Parse()
    35  
    36  	fmt.Println(c)
    37  	fmt.Println("entries:", entries)
    38  
    39  	start := time.Now()
    40  	switch c {
    41  	case "cache":
    42  		cache := cache.New(cache.DefaultOptions)
    43  		for i := 0; i < entries; i++ {
    44  			k, v := genKV(i)
    45  			cache.Set(k, v)
    46  		}
    47  
    48  	case "cache-noevict":
    49  		options := cache.DefaultOptions
    50  		options.DisableEvict = true
    51  		cache := cache.New(options)
    52  		for i := 0; i < entries; i++ {
    53  			k, v := genKV(i)
    54  			cache.Set(k, v)
    55  		}
    56  
    57  	case "stdmap":
    58  		m := make(map[string][]byte)
    59  		for i := 0; i < entries; i++ {
    60  			k, v := genKV(i)
    61  			m[string(k)] = v
    62  		}
    63  	}
    64  	cost := time.Since(start)
    65  
    66  	var mem runtime.MemStats
    67  	var stat debug.GCStats
    68  
    69  	runtime.ReadMemStats(&mem)
    70  	debug.ReadGCStats(&stat)
    71  
    72  	fmt.Println("alloc:", mem.Alloc/1024/1024, "mb")
    73  	fmt.Println("gcsys:", mem.GCSys/1024/1024, "mb")
    74  	fmt.Println("heap inuse:", mem.HeapInuse/1024/1024, "mb")
    75  	fmt.Println("heap object:", mem.HeapObjects/1024, "k")
    76  	fmt.Println("gc:", stat.NumGC)
    77  	fmt.Println("pause:", gcPause())
    78  	fmt.Println("cost:", cost)
    79  }