Environment.TickCount VS DateTime.Now [英] Environment.TickCount vs DateTime.Now

查看:491
本文介绍了Environment.TickCount VS DateTime.Now的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

时它曾经确定使用Environment.TickCount计算时间跨度?

  INT开始= Environment.TickCount;
//做的东西
INT持续时间= Environment.TickCount  - 启动;
Console.WriteLine(难道那+时间MS);
 

由于计时单位计数签署并在25天后(它需要50天的时间全部命中32位,但你必须报废签位,如果​​你想使数学任何意义)将翻转,现在看来似乎太冒险是有用的。

我用DateTime.Now代替。这是做到这一点的最好方法是什么?

 的日期时间开始= DateTime.Now;
//做的东西
时间跨度时间= DateTime.Now  - 启动;
Console.WriteLine(难道那+ duration.TotalMilliseconds +MS);
 

解决方案

使用秒表类。有MSDN上一个体面的例子:<一href="http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx">http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

 秒表,秒表= Stopwatch.StartNew();
    Thread.sleep代码(10000);
    stopWatch.Stop();
    //获取经过时间作为时间跨度值。
    时间跨度TS = stopWatch.Elapsed;
 

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");

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.

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");

解决方案

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 VS DateTime.Now的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆