为什么 C# 中秒表的 ElapsedTicks 折叠?

Why ElapsedTicks of Stopwatch in C# is collapsed?

我想知道为什么 ElapsedTicks 值差异会因为更改 region.

代码

 Stopwatch timer = new Stopwatch( );
 #region "TimeCheck1"
 timer.Start( );
 string s1 = "HelloWorld";
 int length = s1.Length;
 int subLength = length / 2;
 string sA = s1.Substring(0, subLength);
 string sB = s1.Substring(subLength, subLength);
 timer.Stop( );
 Console.WriteLine("String: " + s1 + " Sub1: " + sA + " Sub2: " + sB + " Timer: " + timer.ElapsedTicks);
 #endregion "TimeCheck1"

 #region "TimeCheck2"
 timer.Start( );
 string s2 = "HelloWorld";
 int length2 = s2.Length;
 int subLength2 = length2 / 2;
 string s2A = subStr(s2, 0, subLength2);
 string s2B = subStr(s2, subLength2, subLength2);
 timer.Stop( );
 Console.WriteLine("String: " + s2 + " Sub1: " + s2A + " Sub2: " + s2B + " Timer: " + timer.ElapsedTicks);
 #endregion "TimeCheck2"

输出 1

String: HelloWorld Sub1: Hello Sub2: World Timer: 12
String: HelloWorld Sub1: Hello Sub2: World Timer: 639

输出 2

交换区域 TimeCheck1 和 TimeCheck2 之后
String: HelloWorld Sub1: Hello Sub2: World Timer: 826
String: HelloWorld Sub1: Hello Sub2: World Timer: 828

为什么会出现这种差异?我这里太糊涂了。

编辑(我希望,这个方法不是问题)

private static string subStr( string str, int index, int len ) {
    string sub = "";
    int c = index;
    len = index + len;
    while( c != len ) {
        sub += str[ c ];
        c++;
    }
    return sub;
}

因为 Stopwatch 取决于 OS 和硬件。

来自Stopwatch.IsHighResolution

The timer used by the Stopwatch class depends on the system hardware and operating system. IsHighResolution is true if the Stopwatch timer is based on a high-resolution performance counter. Otherwise, IsHighResolution is false, which indicates that the Stopwatch timer is based on the system timer.

每个间隔的刻度数越多,分辨率越高。这意味着 Stopwatch 会更准确。

编辑:正如 CodeCaster 提到的,有时 Stopwatch 必须预热。可能是因为它使用高分辨率状态的硬件。根据我的经验,我可以告诉你这是真的。尝试只启动一个秒表。并计算刻度之间的差异(当前 - 开始)。在开始后增加睡眠可能也有帮助。

您错误地使用了秒表。您应该在第二次调用时调用 Restart(),而不是 Start()。如果你改变它,那么你的措施就会得到一致的结果

来自 MSDN StopWatch.Start

When a Stopwatch instance measures more than one interval, the Start method resumes measuring time from the current elapsed time value. A Stopwatch instance calculates and retains the cumulative elapsed time across multiple time intervals, until the instance is reset. Use the Reset method before calling Start to clear the cumulative elapsed time in a Stopwatch instance. Use the Restart method to Reset and Start the Stopwatch with a single command.

 Stopwatch timer = new Stopwatch( );
 timer.Start( );

 #region "TimeCheck1"
 .....
 #endregion "TimeCheck1"

 timer.Restart( );
 #region "TimeCheck2" 
 ....
 #endregion

现在,如果您反转区域,则测量结果是一致的。您可以看到您的 subStr 在其第一个 运行.

上受到了性能影响