Skip to content

Instantly share code, notes, and snippets.

@ep4sh
Created October 6, 2020 19:39
Show Gist options
  • Save ep4sh/51a5d4427979fcdeba6ec8db1a656be7 to your computer and use it in GitHub Desktop.
Save ep4sh/51a5d4427979fcdeba6ec8db1a656be7 to your computer and use it in GitHub Desktop.
Worker Mem consumption with/without pointers

The approximated result is:

without pointer:
Alloc = 1082 KiB	TotalAlloc = 3301 KiB	Sys = 71040 KiB	NumGC = 1
Alloc = 1112 KiB	TotalAlloc = 3311 KiB	Sys = 71552 KiB	NumGC = 1
Alloc = 1110 KiB	TotalAlloc = 3302 KiB	Sys = 71296 KiB NumGC = 1


with pointer (less mem consumption)
Alloc = 1048 KiB	TotalAlloc = 3325 KiB	Sys = 71808 KiB	NumGC = 1
Alloc = 1047 KiB	TotalAlloc = 3326 KiB	Sys = 71040 KiB	NumGC = 1
Alloc = 1037 KiB	TotalAlloc = 3321 KiB	Sys = 71296 KiB NumGC = 1

The code is the following:

package main

import (
	"fmt"
	"math/rand"
	"runtime"
)

type Worker struct {
	id    int
	ablob int64
	bblob int64
	cblob int64
}

func (w Worker) procc(c chan int) {
	for {
		fmt.Println(w.ablob * w.bblob * w.cblob)
		fmt.Printf("%d -- %d \n", w.id, <-c)
	}
}

func main() {

	c := make(chan int)
	for i := 0; i <= 1000; i++ {
		worker := Worker{id: i, cblob: 900000000000000000, bblob: 900000000000000000, ablob: 900000000000000000}
		go worker.procc(c)
	}

	for j := 0; j < 100000; j++ {
		c <- rand.Int()
	}

	PrintMemUsage()
}

func PrintMemUsage() {
	var m runtime.MemStats
	runtime.ReadMemStats(&m)
	// For info on each, see: https://golang.org/pkg/runtime/#MemStats
	fmt.Printf("Alloc = %v KiB", bToMb(m.Alloc))
	fmt.Printf("\tTotalAlloc = %v KiB", bToMb(m.TotalAlloc))
	fmt.Printf("\tSys = %v KiB", bToMb(m.Sys))
	fmt.Printf("\tNumGC = %v\n", m.NumGC)
}

func bToMb(b uint64) uint64 {
	return b / 1024
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment