@manhng

Welcome to my blog!

Benchmarking with Stopwatch

May 30, 2021 13:03

Benchmarking with Stopwatch (C#) (edit)

  • Measuring code execution time
  • How to measure code execution time in .NET?
  • How to measure code performance in .NET?
  • Display: stopwatch.ElapsedMilliseconds

A High-Precision Stopwatch for C# - CodeProject

Simple Performance Measurement Tool Stopwatch (c-sharpcorner.com)

c# - Stopwatch for performance testing - Stack Overflow

Comparing implementations with BenchmarkDotnet - Meziantou's blog

On Abstractions and For-Each Performance in C# (infoq.com)

15 Simple ASP.NET Performance Tuning Tips – Stackify

Dapper vs Entity Framework vs ADO.NET Performance Benchmarking (exceptionnotfound.net)

exceptionnotfound/ORMBenchmarksTest (github.com)

  • Entity Framework is markedly slower than either ADO.NET or Dapper.NET, on the order of 3-10 times slower.
  • Dapper.NET is unquestionably faster than EF and slightly faster than straight ADO.NET

Basic 0

using System.Diagnostics;
// ...
Stopwatch sw = new Stopwatch();
sw.Start();
// ...
sw.Stop();
Console.WriteLine("Elapsed={0}",sw.Elapsed);

Basic 1

// Microseconds
int microSeconds = (int)(sw.ElapsedTicks * 1.0e6 / Stopwatch.Frequency + 0.4999);
// Nanoseconds (estimation)
int nanoSeconds = (int)(sw.ElapsedTicks * 1.0e9 / Stopwatch.Frequency + 0.4999);

Basic 2

// Get the elapsed time as a TimeSpan value. 
TimeSpan ts = stopWatch.Elapsed;

// Format and display the TimeSpan value.
string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}", ts.Hours, ts.Minutes, ts.Seconds, ts.Milliseconds / 10);
Console.WriteLine(
"RunTime " + elapsedTime);

Basic 3

// Display the timer frequency and resolution. 
if (Stopwatch.IsHighResolution)
{
....
}

long frequency = Stopwatch.Frequency;
Console.WriteLine(
" Timer frequency in ticks per second = {0}", frequency);
long nanosecPerTick = (1000L*1000L*1000L) / frequency;
Console.WriteLine(
" Timer is accurate within {0} nanoseconds", nanosecPerTick);

Advanced

// Method #1
var stopwatch = new Stopwatch ();
stopwatch.Start ();
LongRunningProcess ();
stopwatch.Stop ();
Console.WriteLine ("Method #1 Total seconds: {0}", stopwatch.Elapsed.TotalSeconds);
// Method #2
using (Benchmark.Start("Method #2")) {
    LongRunningProcess();
}
public class Benchmark : IDisposable
{
    Stopwatch _watch;
    string _name;

    public static Benchmark Start (string name)
    {
        return new Benchmark(name);
    }

    private Benchmark (string name)
    {
        _name = name;
        _watch = new Stopwatch();
        _watch.Start();
    }

    #region IDisposable implementation

    // Dispose stops stopwatch and prints time, could do anything here
    public void Dispose()
    {
        _watch.Stop();
        Console.WriteLine("{0} Total seconds: {1}", _name, _watch.Elapsed.TotalSeconds);
    }

    #endregion
}

Categories

Recent posts