package main

import (
	"fmt"
	"os"
	"runtime"
	"syscall"
	"time"
	"unsafe"
)

// resident returns the MiB of b that is resident, using mincore.
func resident(b []byte) int {
	const pg = 4096
	n := (len(b) + pg - 1) / pg
	vec := make([]byte, n)
	p := uintptr(unsafe.Pointer(&b[0]))
	_, _, e := syscall.Syscall(syscall.SYS_MINCORE, p, uintptr(len(b)), uintptr(unsafe.Pointer(&vec[0])))
	if e != 0 {
		panic(e)
	}
	c := 0
	for _, v := range vec {
		c += int(v & 1)
	}
	return c * pg >> 20
}

func main() {
	var d [][]byte
	var ms runtime.MemStats
	for i := range 60 {
		d = append(d, make([]byte, 400<<20))
		runtime.ReadMemStats(&ms)
		fmt.Fprintf(os.Stdout, "i=%d addr=%p gc=%d released=%dMiB idle=%dMiB resident:", i, &d[i][0], ms.NumGC, ms.HeapReleased>>20, (ms.HeapIdle)>>20)
		for j := range d {
			if r := resident(d[j]); r > 0 {
				fmt.Printf(" [%d]=%d", j, r)
			}
		}
		fmt.Println()
		time.Sleep(200 * time.Millisecond)
	}
}
