我有代码可以衡量一些操作花费的时间。如果日间节能在操作过程中生效,我会得到不准确的数据。
例如,我正在做
DateTime startAt = DateTime.Now;
DoOperation(); //day light saving takes effect in the middle
int seconds = (DateTime.Now - startAt).TotalSeconds;
//second has wrong seconds
有没有办法衡量这个?
由于
答案 0 :(得分:6)
使用StopWatch
类代替......例如
var stopWatch = new StopWatch();
stopWatch.Start();
//code here
stopWatch.Stop()
Console.WriteLine("elapsed millisconds " + stopwatch.ElapsedMilliseconds);
答案 1 :(得分:1)
假设您使用的是c#,则可以使用DateTime.UtcNow
代替DateTime.Now
答案 2 :(得分:0)
同样在.NET中有一个DateTime.Ticks ...可能会更准确一些,如果需要的话可以在XP上运行... 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