当我的计算机进入睡眠状态时,C# 秒表会暂停吗?

Does C# Stopwatch pause when my computer goes to sleep?

我正在使用秒表测量我的程序(用 C# 编写)的运行时间。我的电脑睡着了,我不知道它显示的时间数据是否正确。那么 Stopwatch 也是在测量睡眠时间还是暂停然后继续?

根据 source code for StopWatch 方法 Start 如下所示:

public void Start() {
    // Calling start on a running Stopwatch is a no-op.
    if(!isRunning) {
        startTimeStamp = GetTimestamp();                 
        isRunning = true;
    }
}

方法 Stop 如下所示:

public void Stop() {
    // Calling stop on a stopped Stopwatch is a no-op.
    if( isRunning) {
        long endTimeStamp = GetTimestamp();                 
        long elapsedThisPeriod = endTimeStamp - startTimeStamp;
        elapsed += elapsedThisPeriod;
        isRunning = false;

        if (elapsed < 0) {
            // When measuring small time periods the StopWatch.Elapsed* 
            // properties can return negative values.  This is due to 
            // bugs in the basic input/output system (BIOS) or the hardware
            // abstraction layer (HAL) on machines with variable-speed CPUs
            // (e.g. Intel SpeedStep).

            elapsed = 0;
        }
    }
}

所以你的问题的答案是: 它通过使用两个时间戳来测量持续时间,从而得出结论,你的计算机是否进入睡眠并不重要.

更新(感谢 Mike 和 Joe): 但是,如果您的计算机正在休眠,它无法 运行 您的程序 - 因此测量的持续时间将是程序 运行ning 的持续时间与计算机休眠的持续时间的总和。 TotalDuration = CalculationDuration + SleepDuration.

计算机进入睡眠状态时秒表不会暂停。

当计算机进入睡眠状态时,它使用 Windows API QueryPerformanceCounter() function, which does not reset the count:

"QueryPerformanceCounter reads the performance counter and returns the total number of ticks that have occurred since the Windows operating system was started, including the time when the machine was in a sleep state such as standby, hibernate, or connected standby."