title: Bash script: write CPU utilization to file (Ubuntu)
body: <p>I would like to write a bash script that writes the current CPU utilization to a file "logfile". I am using Intel® Core™ i7-4500U CPU @ 1.80GHz × 4 and Ubuntu 15.10.</p>
  
  <p>I have seen similar questions asked already in this forum, however not all of my questions were answered to 100 percent. By my research I came up with two possible ways of achieving my goal. First one is</p>
  
  <pre><code>    mpstat | grep "all" | awk '{ print $3 + $5; }' &gt;&gt; logfile
  </code></pre>
  
  <p>(adding user CPU and system CPU) and my second candidate is</p>
  
  <pre><code>   mpstat | grep "all" | awk '{ print 100 - $12; }' &gt;&gt; logfile
  </code></pre>
  
  <p>(100 - %idle CPU). Which one of those two is the right one for me if I am interested in the total CPU utilization (so all components that count in some form as CPU should be included).</p>
  
  <p>Another question: By what I have learned by reading other threads, I think my second candidate</p>
  
  <pre><code>   mpstat | grep "all" | awk '{ print 100 - $12; }' &gt;&gt; logfile
  </code></pre>
  
  <p>should be quite accurate. However, when I open the "System Monitor" and monitor the "CPU History" I observe significantly different CPU utilization. Another thing is that the values in the System Monitor are very dynamic (CPU varies between 4% and 18%) whereas over the same period the outcome of the second command remains almost constant. Has someone an explanation for that?</p>
  
  <p>Many thanks for all comments! </p>