CodeBlanks Logo Icon CodeBlanks

The runtime package

Learn the basic functions of the runtime package.

The runtime package

The runtime package lets you talk to the Go runtime underneath your program: scheduler, memory and stack information.

fmt.Println(runtime.NumCPU())        // number of cores
fmt.Println(runtime.NumGoroutine())  // live goroutines
fmt.Println(runtime.GOOS, runtime.GOARCH)

These functions are for diagnosis and monitoring; tying application logic to them is usually not a good idea.

runtime/metrics

runtime/metrics, added in Go 1.16, offers cheaper measurements with stable names than ReadMemStats:

s := []metrics.Sample{{Name: "/sched/goroutines:goroutines"}}
metrics.Read(s)
fmt.Println(s[0].Value.Uint64())

All names are listed by metrics.All(); Prometheus clients use this package too.

Practice Goroutine metric

Read the "/sched/goroutines:goroutines" sample with runtime/metrics and print whether the value is greater than 0.

Starter code

main.go
package main

import (
    "fmt"
    "runtime/metrics"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "fmt"
    "runtime/metrics"
)

func main() {
    s := []metrics.Sample{{Name: "/sched/goroutines:goroutines"}}
    metrics.Read(s)
    fmt.Println(s[0].Value.Uint64() > 0)
}

Expected output

true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is <code>runtime.GOOS</code> determined?

  • The user sets it
  • At compile time (the target OS) Correct answer
  • It is re-measured on each run
  • During a GC cycle

Explanation: GOOS and GOARCH are the target of the built binary; when cross-compiling they can differ from the build machine.

2 Core count

Question
n := runtime.____()
Answer
n := runtime.NumCPU()

Explanation: NumCPU returns the number of logical CPUs the process can use.

3 runtime function

Term Meaning
NumCPU Logical CPUs
NumGoroutine Live goroutines
Version Go version
metrics.Read Named measurements

All lessons in Expert