开发者

measure elapsed time accounting day light saving

I have code that measure how much time some operation took. If day light saving takes effect in the middle of the operation, I get inaccurate data.

So for example, I am doing

DateTime startAt = DateTime.Now;
DoOperation(); //day light saving takes effect in the 开发者_开发技巧middle
int seconds = (DateTime.Now - startAt).TotalSeconds;
//second has wrong seconds

Is there a way to measure this?

Thanks


Use the StopWatch class instead...eg

var stopWatch = new StopWatch();
stopWatch.Start();
//code here
stopWatch.Stop()
Console.WriteLine("elapsed millisconds " + stopwatch.ElapsedMilliseconds);


Assuming you are using c# you could use DateTime.UtcNow instead of DateTime.Now


Also in .NET there is a DateTime.Ticks... which may be a bit more accurate and work on XP if need be... Example shown on MSDN:

DateTime centuryBegin = new DateTime(2001, 1, 1);
DateTime currentDate = DateTime.Now;

long elapsedTicks = currentDate.Ticks - centuryBegin.Ticks;
TimeSpan elapsedSpan = new TimeSpan(elapsedTicks);

Console.WriteLine("Elapsed from the beginning of the century to {0:f}:", 
                   currentDate);
Console.WriteLine("   {0:N0} nanoseconds", elapsedTicks * 100);
Console.WriteLine("   {0:N0} ticks", elapsedTicks);
Console.WriteLine("   {0:N2} seconds", elapsedSpan.TotalSeconds);
Console.WriteLine("   {0:N2} minutes", elapsedSpan.TotalMinutes);
Console.WriteLine("   {0:N0} days, {1} hours, {2} minutes, {3} seconds", 
                  elapsedSpan.Days, elapsedSpan.Hours, 
                  elapsedSpan.Minutes, elapsedSpan.Seconds);

// If run on December 14, 2007, at 15:23, this example displays the
// following output to the console:
//    Elapsed from the beginning of the century to Friday, December 14, 2007 3:23 PM:
//          219,338,580,000,000,000 nanoseconds
//          2,193,385,800,000,000 ticks
//          219,338,580.00 seconds
//          3,655,643.00 minutes
//          2,538 days, 15 hours, 23 minutes, 0 seconds
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜