StopWatchのタイミングをデリゲートまたはラムダでラップしますか?

StackOverflow https://stackoverflow.com/questions/232848

  •  04-07-2019
  •  | 
  •  

質問

私はこのようなコードを書いており、少し速くて汚いタイミングをしています:

var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < 1000; i++)
{
    b = DoStuff(s);
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

確かに、このビットのタイミングコードを(神は禁じています)カットアンドペーストを数回行い、 DoStuff(s) DoSomethingElse(s)

Delegateとして実行できることはわかっていますが、ラムダ方式については疑問に思っています。

役に立ちましたか?

解決

Stopwatchクラスの拡張はどうですか?

public static class StopwatchExtensions
{
    public static long Time(this Stopwatch sw, Action action, int iterations)
    {
        sw.Reset();
        sw.Start(); 
        for (int i = 0; i < iterations; i++)
        {
            action();
        }
        sw.Stop();

        return sw.ElapsedMilliseconds;
    }
}

次のように呼び出します:

var s = new Stopwatch();
Console.WriteLine(s.Time(() => DoStuff(), 1000));

<!> quot; iterations <!> quot;を省略する別のオーバーロードを追加できます。パラメータを使用して、このバージョンをデフォルト値(1000など)で呼び出します。

他のヒント

これまで使用してきたもの:

public class DisposableStopwatch: IDisposable {
    private readonly Stopwatch sw;
    private readonly Action<TimeSpan> f;

    public DisposableStopwatch(Action<TimeSpan> f) {
        this.f = f;
        sw = Stopwatch.StartNew();
    }

    public void Dispose() {
        sw.Stop();
        f(sw.Elapsed);
    }
}

使用法:

using (new DisposableStopwatch(t => Console.WriteLine("{0} elapsed", t))) {
  // do stuff that I want to measure
}

使用しているクラス(または基本クラス)の拡張メソッドを作成してみてください。

コールは次のようになります。

Stopwatch sw = MyObject.TimedFor(1000, () => DoStuff(s));

次に拡張メソッド:

public static Stopwatch TimedFor(this DependencyObject source, Int32 loops, Action action)
{
var sw = new Stopwatch();
sw.Start();
for (int i = 0; i < loops; ++i)
{
    action.Invoke();
}
sw.Stop();

return sw;
}

DependencyObjectから派生するオブジェクトはすべて、TimedFor(..)を呼び出すことができます。関数は、ref paramsを介して戻り値を提供するように簡単に調整できます。

-

機能をどのクラス/オブジェクトにも結び付けたくない場合は、次のようにすることができます:

public class Timing
{
  public static Stopwatch TimedFor(Action action, Int32 loops)
  {
    var sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < loops; ++i)
    {
      action.Invoke();
    }
    sw.Stop();

    return sw;
  }
}

その後、次のように使用できます:

Stopwatch sw = Timing.TimedFor(() => DoStuff(s), 1000);

これに失敗した場合、この回答はまともな<!> quot; generic <!> quot;能力:

StopWatchのタイミングをデリゲートまたはラムダでラップしますか

StopWatchクラスは、エラー時にDisposedまたはStoppedである必要はありません。したがって、時間いくつかのアクションの最も簡単なコードは

public partial class With
{
    public static long Benchmark(Action action)
    {
        var stopwatch = Stopwatch.StartNew();
        action();
        stopwatch.Stop();
        return stopwatch.ElapsedMilliseconds;
    }
}

サンプル呼び出しコード

public void Execute(Action action)
{
    var time = With.Benchmark(action);
    log.DebugFormat(“Did action in {0} ms.”, time);
}

繰り返しをNコードに含めるという考えは好きではありません。 <=>反復の実行を処理する別のメソッドまたは拡張機能をいつでも作成できます。

public partial class With
{
    public static void Iterations(int n, Action action)
    {
        for(int count = 0; count < n; count++)
            action();
    }
}

サンプル呼び出しコード

public void Execute(Action action, int n)
{
    var time = With.Benchmark(With.Iterations(n, action));
    log.DebugFormat(“Did action {0} times in {1} ms.”, n, time);
}

拡張メソッドのバージョンは次のとおりです

public static class Extensions
{
    public static long Benchmark(this Action action)
    {
        return With.Benchmark(action);
    }

    public static Action Iterations(this Action action, int n)
    {
        return () => With.Iterations(n, action);
    }
}

サンプル呼び出しコード

public void Execute(Action action, int n)
{
    var time = action.Iterations(n).Benchmark()
    log.DebugFormat(“Did action {0} times in {1} ms.”, n, time);
}

静的メソッドと拡張メソッド(反復とベンチマークを組み合わせたもの)をテストしたところ、予想実行時間と実際の実行時間の差は<!> lt; = 1 msです。

先ほど、Actionを使用してメソッドを簡単にプロファイリングするためにStopwatchをラップする簡単なCodeProfilerクラスを作成しました。 http://www.improve.dk/ blog / 2008/04/16 / profiling-code-the-easy-way

また、マルチスレッド化されたコードのプロファイルを簡単に作成できます。次の例は、1〜16スレッドでアクションラムダをプロファイルします。

static void Main(string[] args)
{
    Action action = () =>
    {
        for (int i = 0; i < 10000000; i++)
            Math.Sqrt(i);
    };

    for(int i=1; i<=16; i++)
        Console.WriteLine(i + " thread(s):\t" + 
            CodeProfiler.ProfileAction(action, 100, i));

    Console.Read();
}

1つの事柄の簡単なタイミングが必要な場合、これは使いやすいです。

  public static class Test {
    public static void Invoke() {
        using( SingleTimer.Start )
            Thread.Sleep( 200 );
        Console.WriteLine( SingleTimer.Elapsed );

        using( SingleTimer.Start ) {
            Thread.Sleep( 300 );
        }
        Console.WriteLine( SingleTimer.Elapsed );
    }
}

public class SingleTimer :IDisposable {
    private Stopwatch stopwatch = new Stopwatch();

    public static readonly SingleTimer timer = new SingleTimer();
    public static SingleTimer Start {
        get {
            timer.stopwatch.Reset();
            timer.stopwatch.Start();
            return timer;
        }
    }

    public void Stop() {
        stopwatch.Stop();
    }
    public void Dispose() {
        stopwatch.Stop();
    }

    public static TimeSpan Elapsed {
        get { return timer.stopwatch.Elapsed; }
    }
}

ラムダに渡したいパラメーターのさまざまなケースをカバーするために、いくつかのメソッドをオーバーロードできます:

public static Stopwatch MeasureTime<T>(int iterations, Action<T> action, T param)
{
    var sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < iterations; i++)
    {
        action.Invoke(param);
    }
    sw.Stop();

    return sw;
}

public static Stopwatch MeasureTime<T, K>(int iterations, Action<T, K> action, T param1, K param2)
{
    var sw = new Stopwatch();
    sw.Start();
    for (int i = 0; i < iterations; i++)
    {
        action.Invoke(param1, param2);
    }
    sw.Stop();

    return sw;
}

代わりに、値を返す必要がある場合はFuncデリゲートを使用できます。各反復で一意の値を使用する必要がある場合は、パラメーターの配列(またはそれ以上)を渡すこともできます。

私にとって拡張機能はintでもう少し直感的に感じられるので、ストップウォッチをインスタンス化したり、リセットを心配したりする必要はもうありません。

つまり、次のとおりです。

static class BenchmarkExtension {

    public static void Times(this int times, string description, Action action) {
        Stopwatch watch = new Stopwatch();
        watch.Start();
        for (int i = 0; i < times; i++) {
            action();
        }
        watch.Stop();
        Console.WriteLine("{0} ... Total time: {1}ms ({2} iterations)", 
            description,  
            watch.ElapsedMilliseconds,
            times);
    }
}

使用例:

var randomStrings = Enumerable.Range(0, 10000)
    .Select(_ => Guid.NewGuid().ToString())
    .ToArray();

50.Times("Add 10,000 random strings to a Dictionary", 
    () => {
        var dict = new Dictionary<string, object>();
        foreach (var str in randomStrings) {
            dict.Add(str, null);
        }
    });

50.Times("Add 10,000 random strings to a SortedList",
    () => {
        var list = new SortedList<string, object>();
        foreach (var str in randomStrings) {
            list.Add(str, null);
        }
    });

サンプル出力:

Add 10,000 random strings to a Dictionary ... Total time: 144ms (50 iterations)
Add 10,000 random strings to a SortedList ... Total time: 4088ms (50 iterations)

Vance MorrisonのCodeTimerクラス(.NETのパフォーマンスの1つ)を使用したい。

彼は、ブログに<!> quot; マネージコードをすばやく簡単に測定:CodeTimers <!> quot;。

MultiSampleCodeTimerなどのクールなものが含まれています。平均と標準偏差の自動計算を行い、結果を非常に簡単に印刷できます。

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top