title: How to Calculate Difference Between 2 Timevals?
body: <p>In my code I have:</p>
  <pre><code>struct timeval arrival_time, struct timeval pickup_time;
  
  sprintf(buf, &quot;Stat-Req-Dispatch:: %lu.%06d\r\n&quot;, (pickup_time.tv_sec - arrival_time.tv_sec),
          (pickup_time.tv_usec - arrival_time.tv_usec));
  </code></pre>
  <p>But I have noticed that this code isn't correct since sometimes the part which comes after <code>.</code> in printing might be negative.</p>
  <p>I tried: <code>struct timeval dispatch_time = pickup_time-arrival_time;</code> but doesn't compile.</p>
  <p>How can I properly print the difference between both times?</p>
  <hr />
  <pre><code>if (pickup_time.tv_usec &lt; arrival_time.tv_usec)
  {
      dispatch_time.tv_sec = pickup_time.tv_sec - arrival_time.tv_sec - 1;
      dispatch_time.tv_usec = pickup_time.tv_usec - arrival_time.tv_usec + 1000000;
  } else
  {
      dispatch_time.tv_sec = pickup_time.tv_sec - arrival_time.tv_sec;
      dispatch_time.tv_usec = pickup_time.tv_usec - arrival_time.tv_usec;
  }
  
  sprintf(buf, &quot;%sStat-Req-Dispatch:: %lu.%06d\r\n&quot;, buf, dispatch_time.tv_sec, dispatch_time.tv_usec);
  </code></pre>