【问题标题】:Absolute Time Measurement绝对时间测量
【发布时间】:2012-04-21 12:10:50
【问题描述】:

当我开始某个进程时,我将 DateTime.Now 记为 StartTime。

在稍后的过程中,我从 DateTime.Now 中减去 StartTime 来计算这两者之间经过的时间 - 从开始时间到当前时间。

现在,问题是这种方法并不总是准确的 - 在处理过程中,时间可能会由窗口使用时间服务器更改,甚至由用户手动更改。

是否还有其他一些如上所述的测量时间的方法将始终正常工作 - 即使同时更改了窗口时间?

【问题讨论】:

  • 太好了,这正是我想要的

标签: c# .net datetime


【解决方案1】:
【解决方案2】:

使用秒表。

var a = Stopwatch.StartNew(); // Initializes and starts running
var b = new Stopwatch(); // Initializes and doesn't start running

var c = a.Elapsed; // TimeSpan

a.Stop();
a.Start();
a.Reset();

秒表本身就像一块手表,因此它不依赖计算机的时钟。 只需从头开始,然后检查 Elapsed 以查看已经过去了多少时间。

【讨论】:

    【解决方案3】:

    你可以利用这个:Get time of Code Execution Using StopWatch

    Stopwatch stopWatch = new Stopwatch();
    stopWatch.Start();
    //instead of this there is line of code that you are going to execute
    Thread.Sleep(10000);
    stopWatch.Stop();
    // Get the elapsed time as a TimeSpan value.
    TimeSpan ts = stopWatch.Elapsed;
    string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
    ts.Hours, ts.Minutes, ts.Seconds,
    ts.Milliseconds / 10);
    Console.WriteLine(elapsedTime);
    Console.ReadLine();
    

    【讨论】:

      猜你喜欢
      • 2016-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-09
      • 1970-01-01
      相关资源
      最近更新 更多