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 天后翻转(达到所有 32 位需要 50 天,但是如果你想对数学有任何意义,你必须废弃有符号的位),似乎风险太大而没有用.
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屋!