【问题标题】:Is .NET Stopwatch standby/sleep/hibernate aware?.NET 秒表是否支持待机/睡眠/休眠?
【发布时间】:2011-12-28 13:16:05
【问题描述】:

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

【问题讨论】:

  • 有趣的问题,我只使用过秒表来进行穷人的分析,所以我从来没有想过。
  • 好问题....试试看,让我们知道:)
  • 从答案中可以看出,这是特定于实现的行为。计数器由操作系统的硬件抽象层包裹,为硬件设计人员提供了很多选择来减少便士。

标签: .net stopwatch


【解决方案1】:

是的。

查看Reflector中的代码显示,如果不是Stopwatch.IsHighResolution,那么它会使用tick count(在我的环境中,值是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;
}

【讨论】:

  • 是的,确实如此。但是非常不准确。看我的回答。
【解决方案2】:

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

  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();
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2011-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多