Skip to content

Instantly share code, notes, and snippets.

@montanaflynn
Created June 15, 2020 06:55
Show Gist options
  • Save montanaflynn/aba42c3015b0d2c54b185724bfedc86a to your computer and use it in GitHub Desktop.
Save montanaflynn/aba42c3015b0d2c54b185724bfedc86a to your computer and use it in GitHub Desktop.
Check memory usage for an array of 1 million integers in Golang
package main
import (
"fmt"
"runtime"
)
// 1e7 is 1 million
var listLength int = 1e7
type memoryStats struct {
allocated string
totalAllocated string
system string
}
// getMemory finds the allocated, totalAllocated and system memory
func getMemory() memoryStats {
var m runtime.MemStats
runtime.ReadMemStats(&m)
return memoryStats{
allocated: fmt.Sprintf("%d MiB", m.Alloc/1024/1024),
totalAllocated: fmt.Sprintf("%d MiB", m.TotalAlloc/1024/1024),
system: fmt.Sprintf("%d MiB", m.Sys/1024/1024),
}
}
func main() {
list := []int{}
fmt.Println("List length:", len(list))
fmt.Printf("Memory usage: %+v\n", getMemory())
for i := 0; i < listLength; i++ {
list = append(list, i)
}
fmt.Println("List length:", len(list))
fmt.Printf("Memory usage: %+v\n", getMemory())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment