title: Prevent excessive CPU usage of Golang background process
body: <p>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:</p>
  
  <pre><code>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] &gt; 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)
      }
  }
  </code></pre>
  
  <p>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. </p>
  
  <p>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 <code>runtime.GOMAXPROCS(1)</code> or not.</p>
  
  <p>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.</p>
  
  <p>What is the best practice here?</p>