15

System.Diagnostics.Stopwatch计算机待机期间是否计算时间?

4

2 回答 2

3

实际上,经过一些测试,它似乎确实计数,但它还差得很远。这就是我所做的:

  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();
        }
    }
}
于 2011-12-28T13:26:48.520 回答
3

是的,它确实。

查看 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;
}
于 2011-12-28T13:27:40.773 回答