我已经在.Net Core 2.2中编写了下一个测试程序,并在3台不同的PC上执行它得到的结果大致相同:第二种执行方法总是执行得更快。
代码:
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
for (int i = 0; i < 10; i++)
{
RunTest();
}
}
private static void RunTest()
{
const long cnt = 1000000000;
var time1 = Test1(cnt);
var time2 = Test2(cnt);
Console.WriteLine($"Done in: {time1} vs {time2} diff: {time1 - time2}");
}
private static TimeSpan Test1(long cnt)
{
var v = 1;
var timer = Stopwatch.StartNew();
for (long i = cnt; i != 0; i--)
{
v = RotateBit(v);
}
timer.Stop();
return timer.Elapsed;
}
private static TimeSpan Test2(long cnt)
{
var v = 1;
var timer = Stopwatch.StartNew();
for (long i = cnt; i != 0; i--)
{
v = RotateBit(v);
}
timer.Stop();
return timer.Elapsed;
}
private static int RotateBit(int v)
{
v = v << 1;
if ((v & 0b0000_1111) == 0)
{
v = 1;
}
return v;
}
}
请注意,Test1
和Test2
方法是绝对复制。
没有第一个Test1
或Test2
的仪表,首先执行的仪表总是快将近2倍:Done in: 00:00:00.8881566 vs 00:00:00.4706360 diff: 00:00:00.4175206
,即使RunTest
方法执行了多次。>
发生这种奇怪行为的原因可能是什么?