Created
March 2, 2022 02:41
-
-
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!
This file contains 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" | |
"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