1

我听说过关于锁“慢”的传言,但直到现在才尝试自己衡量它的性能。对其进行基准测试的正确方法是什么?我使用下面的代码产生一致的结果,但我仍然不确定我是否正确执行。

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 |
4

0 回答 0