Created
June 15, 2020 06:55
-
-
Save montanaflynn/aba42c3015b0d2c54b185724bfedc86a to your computer and use it in GitHub Desktop.
Check memory usage for an array of 1 million integers in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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