title: How to ensure a timestamp is always unique?
body: <p>I'm using timestamps to temporally order concurrent changes in my program, and require that each timestamp of a change be unique. However, I've discovered that simply calling <code>DateTime.Now</code> is insufficient, as it will often return the same value if called in quick succession.</p>
  
  <p>I have some thoughts, but nothing strikes me as the "best" solution to this. Is there a method I can write that will guarantee each successive call produces a unique <code>DateTime</code>?</p>
  
  <p>Should I perhaps be using a different type for this, maybe a long int? <code>DateTime</code> has the obvious advantage of being easily interpretable as a real time, unlike, say, an incremental counter.</p>
  
  <p><strong>Update:</strong> Here's what I ended up coding as a simple compromise solution that still allows me to use <code>DateTime</code> as my temporal key, while ensuring uniqueness each time the method is called:</p>
  
  <pre><code>private static long _lastTime; // records the 64-bit tick value of the last time
  private static object _timeLock = new object();
  
  internal static DateTime GetCurrentTime() {
      lock ( _timeLock ) { // prevent concurrent access to ensure uniqueness
          DateTime result = DateTime.UtcNow;
          if ( result.Ticks &lt;= _lastTime )
              result = new DateTime( _lastTime + 1 );
          _lastTime = result.Ticks;
          return result;
      }
  }
  </code></pre>
  
  <p>Because each tick value is only one 10-millionth of a second, this method only introduces noticeable clock skew when called on the order of 10 million times per second (which, by the way, it is efficient enough to execute at), meaning it's perfectly acceptable for my purposes.</p>
  
  <p>Here is some test code:</p>
  
  <pre><code>DateTime start = DateTime.UtcNow;
  DateTime prev = Kernel.GetCurrentTime();
  Debug.WriteLine( "Start time : " + start.TimeOfDay );
  Debug.WriteLine( "Start value: " + prev.TimeOfDay );
  for ( int i = 0; i &lt; 10000000; i++ ) {
      var now = Kernel.GetCurrentTime();
      Debug.Assert( now &gt; prev ); // no failures here!
      prev = now;
  }
  DateTime end = DateTime.UtcNow;
  Debug.WriteLine( "End time:    " + end.TimeOfDay );
  Debug.WriteLine( "End value:   " + prev.TimeOfDay );
  Debug.WriteLine( "Skew:        " + ( prev - end ) );
  Debug.WriteLine( "GetCurrentTime test completed in: " + ( end - start ) );
  </code></pre>
  
  <p>...and the results:</p>
  
  <pre><code>Start time:  15:44:07.3405024
  Start value: 15:44:07.3405024
  End time:    15:44:07.8355307
  End value:   15:44:08.3417124
  Skew:        00:00:00.5061817
  GetCurrentTime test completed in: 00:00:00.4950283
  </code></pre>
  
  <p>So in other words, in half a second it generated 10 million <em>unique</em> timestamps, and the final result was only pushed ahead by half a second. In real-world applications the skew would be unnoticeable.</p>