Saturday, March 16, 2013

DateTime.Now vs DateTime.UtcNow

Please note that this post does not take into account any other perspective of when to use DateTime.Now or DateTime.UtcNow other than performance.

This morning I tried to find numbers that compare DateTime.Now and DateTime.UtcNow but all I found was long discussions on the subject of when to use them. So I decided to write a quick sample myself to see.

Last value was 2013-03-16 12:50:18
DateTime.Now:           00:00:06.6733481 for 10000000 iterations
Last value was 2013-03-16 11:50:18
DateTime.UtcNow:        00:00:00.0741262 for 10000000 iterations
DateTime.UtcNow is 1,11% of DateTime.Now




   1:  class Program
   2:  {
   3:      static void Main(string[] args)
   4:      {
   5:          const int iterations = 10000000;
   6:          DateTime dt = DateTime.UtcNow;
   7:          Stopwatch sw = Stopwatch.StartNew();
   8:          for (int i = 0; i < iterations; i++)
   9:              dt = DateTime.Now;
  10:          sw.Stop();
  11:          Console.WriteLine("Last value was {0}", dt);
  12:          Console.WriteLine("DateTime.Now:\t\t{0} for {1} iterations", sw.Elapsed, iterations);
  13:          double nowMs = sw.ElapsedMilliseconds;
  14:          sw = Stopwatch.StartNew();
  15:          for (int i = 0; i < iterations; i++)
  16:              dt = DateTime.UtcNow;
  17:          sw.Stop();
  18:          Console.WriteLine("Last value was {0}", dt);
  19:          Console.WriteLine("DateTime.UtcNow:\t{0} for {1} iterations", sw.Elapsed, iterations);
  20:          double utcNowMs = sw.ElapsedMilliseconds;
  21:          Console.WriteLine("DateTime.UtcNow is {0:0.00}% of DateTime.Now", CalcPercentage(utcNowMs, nowMs));
  22:          Console.ReadLine();
  23:      }
  24:      private static double CalcPercentage(double value, double max)
  25:      {
  26:          double p = (100.0 / max);
  27:          return p * value;
  28:      }
  29:  }

No comments:

Post a Comment