title: timeval_subtract explanation
body: <p>With the &quot;timeval_subtract&quot; function to find the time elapsed between two struct timeval types, can someone please explain the purpose of and step by step maths used to &quot;Perform the carry for the later subtraction by updating y&quot; and other sections? I understand the purpose of the function and how to implement it within a program, but I would like to understand how it works inside and cannot find any explanations of this anywhere, and I can't seem to wrap my head around it.</p>
  <pre><code>int timeval_subtract (struct timeval *result, struct timeval *x,struct timeval  *y)  
  {  
    /* Perform the carry for the later subtraction by updating y. */  
    if (x-&gt;tv_usec &lt; y-&gt;tv_usec) {  
      int nsec = (y-&gt;tv_usec - x-&gt;tv_usec) / 1000000 + 1;  
      y-&gt;tv_usec -= 1000000 * nsec;  
      y-&gt;tv_sec += nsec;  
    }  
    if (x-&gt;tv_usec - y-&gt;tv_usec &gt; 1000000) {  
      int nsec = (y-&gt;tv_usec - x-&gt;tv_usec) / 1000000;  
      y-&gt;tv_usec += 1000000 * nsec;  
      y-&gt;tv_sec -= nsec;  
    }  
    
    /* Compute the time remaining to wait.
       tv_usec is certainly positive. */  
    result-&gt;tv_sec = x-&gt;tv_sec - y-&gt;tv_sec;  
    result-&gt;tv_usec = x-&gt;tv_usec - y-&gt;tv_usec;  
    
    /* Return 1 if result is negative. */  
    return x-&gt;tv_sec &lt; y-&gt;tv_sec;  
  }
  </code></pre>
  <p>It is a function described in relation to the GNU C library for determining an elapsed time <a href="https://ftp.gnu.org/old-gnu/Manuals/glibc-2.2.5/html_node/Elapsed-Time.html" rel="nofollow noreferrer">https://ftp.gnu.org/old-gnu/Manuals/glibc-2.2.5/html_node/Elapsed-Time.html</a>  so I am not looking for improvements but simply an explanation of why the dividing and adding and subtracting and multiplying within it. What do these specific arithmetic operations achieve?/Why are they done/not done? I have done the stepping through but still can'y get my head around it. I will continue to do so until I do (and even after someone explains it to me) but I was hoping to get some insight from someone who understands it already. The platform is UNIX, which I am new to using, but I don't think it changes the operations that are taking place inside the function. It is more a question about the arithmetic being performed than the algorithm being used.</p>