github.com/fiatjaf/generic-ristretto@v0.0.1/contrib/demo/node.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"runtime"
     6  	"unsafe"
     7  
     8  	"github.com/fiatjaf/generic-ristretto/z"
     9  	"github.com/dustin/go-humanize"
    10  )
    11  
    12  type node struct {
    13  	val  int
    14  	next *node
    15  }
    16  
    17  var nodeSz = int(unsafe.Sizeof(node{}))
    18  var alloc *z.Allocator
    19  
    20  func printNode(n *node) {
    21  	if n == nil {
    22  		return
    23  	}
    24  	if n.val%100000 == 0 {
    25  		fmt.Printf("node: %d\n", n.val)
    26  	}
    27  	printNode(n.next)
    28  }
    29  
    30  func main() {
    31  	N := 2000001
    32  	root := newNode(-1)
    33  	n := root
    34  	for i := 0; i < N; i++ {
    35  		nn := newNode(i)
    36  		n.next = nn
    37  		n = nn
    38  	}
    39  	fmt.Printf("Allocated memory: %s Objects: %d\n",
    40  		humanize.IBytes(uint64(z.NumAllocBytes())), N)
    41  
    42  	runtime.GC()
    43  	printNode(root)
    44  	fmt.Println("printing done")
    45  
    46  	if alloc != nil {
    47  		alloc.Release()
    48  	} else {
    49  		n = root
    50  		for n != nil {
    51  			left := n
    52  			n = n.next
    53  			freeNode(left)
    54  		}
    55  	}
    56  	fmt.Printf("After freeing. Allocated memory: %d\n", z.NumAllocBytes())
    57  
    58  	var ms runtime.MemStats
    59  	runtime.ReadMemStats(&ms)
    60  	fmt.Printf("HeapAlloc: %s\n", humanize.IBytes(ms.HeapAlloc))
    61  }