Dot-Net

.NET 秒錶是否支持待機/睡眠/休眠?

  • December 28, 2011

System.Diagnostics.Stopwatch電腦待機期間是否計算時間?

是的,它確實。

查看 Reflector 中的程式碼表明,如果不是Stopwatch.IsHighResolution,那麼它將使用滴答計數(在我的環境中,值是false所以它將使用DateTime.UtcNow.Ticks):

public void Start()
{
   if (!this.isRunning)
   {
       this.startTimeStamp = GetTimestamp();
       this.isRunning = true;
   }
}



public static long GetTimestamp()
{
   if (IsHighResolution)
   {
       long num = 0L;
       SafeNativeMethods.QueryPerformanceCounter(out num);
       return num;
   }
   return DateTime.UtcNow.Ticks;
}

實際上,經過一些測試,它似乎確實計數,但它還差得很遠。這就是我所做的:

  1. 寫了下面的程式碼
  2. 執行它,並立即將我的電腦置於睡眠模式
  3. 等了 10 秒,然後把我的電腦恢復了

結果是Elapsed超過4分鐘的令人震驚的時間。走開。所以我不會將其用作任何類型的基準。

這是我使用的程式碼:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TestingCode
{
   class Program
   {
       static void Main(string[] args)
       {
           Stopwatch testing = new Stopwatch();

           testing.Start();

           Console.WriteLine("Press any key to stop timer");
           Console.ReadKey();

           testing.Stop();

           Console.WriteLine("Elapsed: {0}", testing.Elapsed);

           Console.WriteLine("Done!!");
           Console.ReadKey();
       }
   }
}

引用自:https://stackoverflow.com/questions/8656390