C#でBenchmarkDotNetを試す。

コンピュータ

BenchmarkDotNetはC#でベンチマークを行うライブラリです。

プロジェクトを作成

cd (mkdir BenchmarkDotNetSample01)
dotnet new console -f net8.0
dotnet add package BenchmarkDotNet

ソースコード

ファイル名:Program.cs

using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;

[MemoryDiagnoser]
public class MyBenchmark
{
    [Params(10, 100, 1000)]
    public int N;

    [Benchmark]
    public void AllocateArray()
    {
        var arr = new int[N];
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        BenchmarkRunner.Run<MyBenchmark>();
    }
}

実行

dotnet run -c Release

Releaseにする必要が有るようです

結果

| Method        | N    | Mean      | Error     | StdDev    | Gen0   | Allocated |
|-------------- |----- |----------:|----------:|----------:|-------:|----------:|
| AllocateArray | 10   |  3.026 ns | 0.0297 ns | 0.0278 ns | 0.0038 |      64 B |
| AllocateArray | 100  |  9.073 ns | 0.0817 ns | 0.0638 ns | 0.0253 |     424 B |
| AllocateArray | 1000 | 70.042 ns | 1.0426 ns | 0.8706 ns | 0.2404 |    4024 B |

// * Hints *
Outliers
  MyBenchmark.AllocateArray: Default -> 3 outliers were removed (10.47 ns..10.69 ns)
  MyBenchmark.AllocateArray: Default -> 2 outliers were removed (76.30 ns, 87.07 ns)

// * Legends *
  N         : Value of the 'N' parameter
  Mean      : Arithmetic mean of all measurements
  Error     : Half of 99.9% confidence interval
  StdDev    : Standard deviation of all measurements
  Gen0      : GC Generation 0 collects per 1000 operations
  Allocated : Allocated memory per single operation (managed only, inclusive, 1KB = 1024B)
  1 ns      : 1 Nanosecond (0.000000001 sec)

// * Diagnostic Output - MemoryDiagnoser *


// ***** BenchmarkRunner: End *****
Run time: 00:00:41 (41.93 sec), executed benchmarks: 3

Global total time: 00:00:47 (47.49 sec), executed benchmarks: 3
// * Artifacts cleanup *
Mean
平均実行時間(1回のメソッド呼び出しあたりの平均時間)
Error
信頼区間の「エラー幅」(統計的な誤差の推定値、通常95%信頼区間)
StdDev
標準偏差(ばらつきの大きさを示す指標。値が小さいほど安定している)
Gen0
世代0(Gen 0)ガベージコレクションの回数/1000オペレーションあたり
Allocated
1回のメソッド呼び出しで割り当てられたメモリ(バイト単位)

Meanの平均時間とAllocatedのメモリ容量外はよくわからないですね。

コメント