I am writing a Go program that watches files and run a system command if one of the files has changed. So far, it works well. I have questions regarding my main "infinite" loop because I don't want it to take all system CPU resources:
runtime.GOMAXPROCS(1)
for {
updatedFiles, _ := GetWatchMap(config)
if !reflect.DeepEqual(filesToWatch, updatedFiles) {
start := time.Now()
_, _ = colorstring.Println(fmt.Sprintf(" [yellow] ⬇ Update detected[white] at [green]%s[white] > updating...", start.Format("15:04:05")))
_, _ = Update(config)
end := time.Now()
elapsed := end.Sub(start)
_, _ = colorstring.Println(fmt.Sprintf(" [green]✅ Done![white] in [yellow]%.2f[white] second(s).", elapsed.Seconds()))
filesToWatch = updatedFiles
} else {
time.Sleep(config.SleepTime)
}
}
So, what I have done is setting GOMAXPROCS, so it only uses "1 CPU/Core", and I have added a configurable sleep time in the else branch.
Without the sleep time, htop shows that the process takes 100% of CPU time (I guess it is 100% of one core?) whatever If I call runtime.GOMAXPROCS(1)
or not.
If I use a sleep time of 30ms on my machine (MacMini i7, 12 Core) htop reports 20% CPU utilisation from the process, which seems OK, but I guess this will vary depending on the computer running the program.
What is the best practice here?