title: Measuring Elapsed Time In Linux (CLOCK_MONOTONIC vs. CLOCK_MONOTONIC_RAW)
body: <p>I am currently trying to talk to a piece of hardware in userspace (underneath the hood, everything is using the spidev kernel driver, but that's a different story).</p>
  
  <p>The hardware will tell me that a command has been completed by indicating so with a special value in a register, that I am reading from.  The hardware also has a requirement to get back to me in a certain time, otherwise the command has failed.  Different commands take different times.</p>
  
  <p>As a result, I am implementing a way to set a timeout and then check for that timeout using <code>clock_gettime()</code>.  In my "set" function, I take the current time and add the time interval I should wait for (usually this anywhere from a few ms to a couple of seconds).  I then store this value for safe keeping later.</p>
  
  <p>In my "check" function, I once again, get the current time and then compare it against the time I have saved.  This seems to work as I had hoped.</p>
  
  <p>Given my use case, should I be using <code>CLOCK_MONOTONIC</code> or <code>CLOCK_MONOTONIC_RAW</code>?  I'm assuming <code>CLOCK_MONOTONIC_RAW</code> is better suited, since I have short intervals that I am checking.  I am worried that such a short interval might represent a system-wide outlier, in which NTP was doing alot of adjusting. Note that my target system is only Linux kernels 4.4 and newer.</p>
  
  <p>Thanks in advance for the help.</p>
  
  <p>Edited to add: given my use case, I need "wall clock" time, not CPU time.   That is, I am checking to see if the hardware has responded in some wall clock time interval.</p>
  
  <p>References:</p>
  
  <ul>
  <li><a href="https://www.cs.rutgers.edu/~pxk/416/notes/c-tutorials/gettime.html" rel="nofollow noreferrer">Rutgers Course Notes</a></li>
  <li><a href="https://stackoverflow.com/questions/14270300/what-is-the-difference-between-clock-monotonic-clock-monotonic-raw">What is the difference between CLOCK_MONOTONIC &amp; CLOCK_MONOTONIC_RAW?</a></li>
  <li><a href="https://www.softwariness.com/articles/monotonic-clocks-windows-and-posix/#POSIX" rel="nofollow noreferrer">Elapsed Time in C Tutorial</a></li>
  </ul>