我听说有传言说锁定速度很慢"但直到现在我都没试过自己衡量它的表现。什么是正确的基准测试方法?我使用下面的代码产生一致的结果,但我仍然不确定我是否正确地做了。
class Program
{
static void Main(string[] args)
{
var summary = BenchmarkRunner.Run<ClassUnderTest>();
}
}
[Config(typeof(Config))]
public class ClassUnderTest
{
private class Config : ManualConfig
{
public Config()
{
Add(Job.LegacyJitX64);
Add(MarkdownExporter.StackOverflow);
}
}
private readonly object _o = new object();
public decimal Money;
[Setup]
public void SetupData()
{
Money = 0;
}
[Benchmark(Baseline = true)]
public decimal NoLock()
{
return ++Money;
}
[Benchmark]
public decimal Lock()
{
lock (_o)
{
return ++Money;
}
}
}
结果:
Host Process Environment Information:
BenchmarkDotNet=v0.9.8.0
OS=Microsoft Windows NT 6.2.9200.0
Processor=Intel(R) Core(TM) i7-4790 CPU 3.60GHz, ProcessorCount=8
Frequency=3507519 ticks, Resolution=285.1018 ns, Timer=ACPI
CLR=MS.NET 4.0.30319.42000, Arch=32-bit RELEASE
GC=Concurrent Workstation
JitModules=clrjit-v4.6.1055.0
Type=ClassUnderTest Mode=Throughput Platform=X64
Jit=LegacyJit GarbageCollection=Concurrent Workstation
Method | Median | StdDev | Scaled |
------- |----------- |---------- |------- |
NoLock | 22.7166 ns | 0.1533 ns | 1.00 |
Lock | 38.0836 ns | 0.2947 ns | 1.68 |