我做了一门课,可以帮助我测量 Ticks 中任何方法的时间。
基本上,它运行测试方法 100x,并强制 GC,然后记录另一个 100x 方法运行所花费的时间。x64 发布 ctrl+f5 VS2012/VS2010
结果如下:
2,914 2,909 2,913 2,909 2,908
2,907 2,909 2,998 2,976 2,855
2,446 2,415 2,435 2,401 2,402
2,402 2,399 2,401 2,401 2,400
2,399 2,400 2,404 2,402 2,401
2,399 2,400 2,402 2,404 2,403
2,401 2,403 2,401 2,400 2,399
2,414 2,405 2,401 2,407 2,399
2,401 2,402 2,401 2,404 2,401
2,404 2,405 2,368 1,577 1,579
1,626 1,578 1,576 1,578 1,577
1,577 1,576 1,578 1,576 1,578
1,577 1,578 1,576 1,578 1,577
1,579 1,585 1,576 1,579 1,577
1,579 1,578 1,579 1,577 1,578
1,577 1,578 1,576 1,578 1,577
1,578 1,599 1,579 1,578 1,582
1,576 1,578 1,576 1,579 1,577
1,578 1,577 1,591 1,577 1,578
1,578 1,576 1,578 1,576 1,578
如您所见,有 3 个阶段,第一个是 ~2,900,第二个是 ~2,400,然后是 ~1,550
可能是什么原因造成的?
更新
我现在强烈怀疑,当我使用英特尔 I5 时,是 cpu turbo boost 干扰了结果。但是,即使我禁用了涡轮增压,它仍然不稳定。同时 Core 2 Quad 产生稳定的基准
测试性能类代码如下:
public static void RunTests(Func<long> myTest)
{
const int numTrials = 100;
Stopwatch sw = new Stopwatch();
double[] sample = new double[numTrials];
Console.WriteLine("Checksum is {0:N0}", myTest());
sw.Start();
myTest();
sw.Stop();
Console.WriteLine("Estimated time per test is {0:N0} ticks\n", sw.ElapsedTicks);
for (int i = 0; i < numTrials; i++)
{
myTest();
}
GC.Collect();
string testName = myTest.Method.Name;
Console.WriteLine("----> Starting benchmark {0}\n", myTest.Method.Name);
for (int i = 0; i < numTrials; i++)
{
sw.Restart();
myTest();
sw.Stop();
sample[i] = sw.ElapsedTicks;
}
double testResult = DataSetAnalysis.Report(sample);
for (int j = 0; j < numTrials; j = j + 5)
Console.WriteLine("{0,8:N0} {1,8:N0} {2,8:N0} {3,8:N0} {4,8:N0}", sample[j], sample[j + 1], sample[j + 2], sample[j + 3], sample[j + 4]);
Console.WriteLine("\n----> End of benchmark");
}