Environment.TickCount与DateTime.Now [英] Environment.TickCount vs DateTime.Now
问题描述
使用 Environment.TickCount
可以计算时间跨度吗?
Is it ever OK to use Environment.TickCount
to calculate time spans?
int start = Environment.TickCount;
// Do stuff
int duration = Environment.TickCount - start;
Console.WriteLine("That took " + duration " ms");
因为 TickCount
已经签名, 25天(需要50天的时间才能达到32位,但是如果你想对数学有任何意义,那么你必须舍弃这个签名的位置),好像这样做太有用了。
Because TickCount
is signed and will rollover after 25 days (it takes 50 days to hit all 32 bits, but you have to scrap the signed bit if you want to make any sense of the math), it seems like it's too risky to be useful.
我正在使用 DateTime.Now
。这是最好的方法吗?
I'm using DateTime.Now
instead. Is this the best way to do this?
DateTime start = DateTime.Now;
// Do stuff
TimeSpan duration = DateTime.Now - start;
Console.WriteLine("That took " + duration.TotalMilliseconds + " ms");
推荐答案
使用秒表类。 msdn上有一个体面的例子: http://msdn.microsoft .com / en-us / library / system.diagnostics.stopwatch.aspx
Use Stopwatch class. There is a decent example on msdn: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx
Stopwatch stopWatch = Stopwatch.StartNew();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;
这篇关于Environment.TickCount与DateTime.Now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!