Go CPU usage more than 100% without goroutine

Hi everyone,

I am new to go. I am wondering why my go program use more than 100% cpu. I got confused because I did not use any goroutine. In the test example below, it used 130% and 200% of CPU in a short period of time during the execution on my machine (I have the other program that processes a file into a map[string]*Person that runs constantly at 200%). Does go automatically implement the program concurrently? I cannot find any material about it due to my poor google skills. Thank you very much for the helps!

package main

import (
	"math/rand"
)

type Person struct {
	Name string
	ID   int
}

func main() {
	n := int(10e6)
	people := make(map[int]*Person)
	for i := 1; i < n; i++ {
		person := RandPerson()
		people[person.ID] = person
	}
	println(len(people), "#####", n)
}

func RandPerson() *Person {
	name := make([]byte, 50)
	for i := 0; i < 50; i++ {
		name[i] = byte(65 + rand.Intn(25))
	}
	id := rand.Intn(10e6)
	return &Person{
		Name: string(name),
		ID:   id,
	}
}

time ./randperson
real 0m11.924s
user 0m17.379s
sys 0m0.544s

Garbage collection. You’re allocating a lot of memory, so there will be certain amount of garbage collection in order to free up memory, even though you’re not generating much garbage in this example.

1 Like

Thank you. Do you know what usually will cause the program run more than 1 thread besides garbage collection? All those “unintentionally” cpu usage should be safe?

I good trick to avoid CPU overhead in this cases is to insert a small delay in the main loop, eg:

time.Sleep(2*time.Millisecond)

Of course you can use a smaller convenient value…

1 Like

If you don’t do any concurrent processing yourself, or use packages that do, I wouldn’t expect any concurrent processing, no. But garbage collection is always concurrent with the rest of the program. This is normal, expected and indeed safe.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.