public class SampleBenchmarkSuite {
[Params(1000)] ⇽--- 避免编译器优化
public int A;
[Params(35)] ⇽---
public int B;
[Benchmark] ⇽--- 用属性标记要进行基准测试的操作
public int Manual() {
int division = A / B;
int remainder = A % B;
return division + remainder; ⇽--- 我们将值返回,这样编译器就不会丢掉计算步骤
}
[Benchmark] ⇽---
public int DivRem() {
int division = Math.DivRem(A, B, out int remainder);
return division + remainder; ⇽---
}
}
using System;
using System.Diagnostics;
using BenchmarkDotNet.Running;
namespace SimpleBenchmarkRunner {
public class Program {
public static void Main(string[] args) {
BenchmarkRunner.Run<SampleBenchmarkSuite>();
}
}
}
4.3.6.2. Math.DivRem()的速度是分别进行除法和求余操作的两倍
4.3.6.3. 使用Stopwatch编写自己的基准测试程序
4.3.6.4. C#
private const int iterations = 1_000_000_000;
private static void runBenchmarks() {
var suite = new SampleBenchmarkSuite {
A = 1000,
B = 35
};
long manualTime = runBenchmark(() => suite.Manual());
long divRemTime = runBenchmark(() => suite.DivRem());
reportResult("Manual", manualTime);
reportResult("DivRem", divRemTime);
}
private static long runBenchmark(Func<int> action) {
var watch = Stopwatch.StartNew();
for (int n = 0; n < iterations; n++) {
action(); ⇽--- 我们在这里调用基准测试代码
}
watch.Stop();
return watch.ElapsedMilliseconds;
}
private static void reportResult(string name, long milliseconds) {
double nanoseconds = milliseconds * 1_000_000;
Console.WriteLine("{0} = {1}ns / operation",
name,
nanoseconds / iterations);
}