usingとIDisposableを使って簡易的な処理計測クラスを作る

先日、書いたusingとDisposerを使って簡易的な処理計測クラスを作ってみました。

using UnityEngine;//for Debug.Log and Debug.Assert
using System;

public class ProcessTimer {
    System.Diagnostics.Stopwatch stopWatch = new System.Diagnostics.Stopwatch();

    public void Start()
    {
        Debug.Assert( !stopWatch.IsRunning );
        stopWatch.Start();
    }

    public void Stop()
    {
        Debug.Assert( stopWatch.IsRunning );
        stopWatch.Stop();
    }

    public void Reset()
    {
        stopWatch.Reset();
    }

    public TimeSpan GetResult()
    {
        return stopWatch.Elapsed;
    }
}

public class ScopedProcessTimer : IDisposable{
    ProcessTimer timer = new ProcessTimer();

    public ScopedProcessTimer()
    {
        timer.Start();
    }

    public void Dispose()
    {
        timer.Stop();
        Debug.Log( "Process Time : " + timer.GetResult().TotalMilliseconds.ToString() + "msec" );
    }
}

最初はDateTime.Nowを使い、その差分で経過時間を図っていたのですが、後からStopWatchという便利なクラスがあることを知って、もはやProcessTimerクラスの存在意義はあまりないです...

こんな感じで使います↓

using ( ScopedProcessTimer spt = new ScopedProcessTimer() )
{
    for(var i = 0; i < 1000; ++i)
    {
        Debug.Log("hoge");
    }
}