title: Measuring time in millisecond precision
body: <p>My program is going to race different sorting algorithms against each other, both in time and space.  I've got space covered, but measuring time is giving me some trouble.  Here is the code that runs the sorts:</p>
  
  <pre><code>void test(short* n, short len) {
    short i, j, a[1024];
  
    for(i=0; i&lt;2; i++) {         // Loop over each sort algo
      memused = 0;               // Initialize memory marker
      for(j=0; j&lt;len; j++)       // Copy scrambled list into fresh array
        a[j] = n[j];             // (Sorting algos are in-place)
                                 // ***Point A***
      switch(i) {                // Pick sorting algo
      case 0:
        selectionSort(a, len);
      case 1:
        quicksort(a, len);
      }
                                 // ***Point B***    
      spc[i][len] = memused;     // Record how much mem was used
    }
  }
  </code></pre>
  
  <p>(I removed some of the sorting algos for simplicity)</p>
  
  <p>Now, I need to measure how much time the sorting algo takes.  The most obvious way to do this is to record the time at point (a) and then subtract that from the time at point (b).  But none of the C time functions are good enough:</p>
  
  <p><strong>time()</strong> gives me time in seconds, but the algos are faster than that, so I need something more accurate.</p>
  
  <p><strong>clock()</strong> gives me CPU ticks since the program started, but seems to round to the nearest 10,000; still not small enough</p>
  
  <p>The <strong>time</strong> shell command works well enough, except that I need to run over 1,000 tests per algorithm, and I need the individual time for each one.</p>
  
  <p>I have no idea what <strong>getrusage()</strong> returns, but it's also too long.</p>
  
  <p>What I need is time in units (significantly, if possible) smaller than the run time of the sorting functions: about 2ms.  So my question is:  Where can I get that?</p>