Skip to content

Instantly share code, notes, and snippets.

@armando-couto
Created March 2, 2022 02:41
Show Gist options
  • Save armando-couto/82719ad7714d073722885d830270cdca to your computer and use it in GitHub Desktop.
Save armando-couto/82719ad7714d073722885d830270cdca to your computer and use it in GitHub Desktop.
In the following example, we combine the fact that goroutines are not garbage collec‐ ted with the runtime’s ability to introspect upon itself and measure the amount of memory allocated before and after goroutine creation!
package main
import (
"fmt"
"runtime"
"sync"
)
func main() {
memConsumed := func() uint64 {
runtime.GC()
var s runtime.MemStats
runtime.ReadMemStats(&s)
return s.Sys
}
var c <-chan interface{}
var wg sync.WaitGroup
noop := func() { wg.Done(); <-c }
const numGoroutines = 1e4
wg.Add(numGoroutines)
before := memConsumed()
for i := numGoroutines; i > 0; i-- {
go noop()
}
wg.Wait()
after := memConsumed()
fmt.Printf("%.3fkb", float64(after-before)/numGoroutines/1000)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment