gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 19:56:43 25 4
gpt4 key购买 nike

我想知道为什么 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;
}

最佳答案

您错误地使用了秒表。您应该在第二次调用时调用 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 在第一次运行时性能受到影响。

关于c# - 为什么 C# 中秒表的 ElapsedTicks 折叠?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32883712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com