Measuring code execution time

Stopwatch measures time elapsed.

// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();

Threading.Thread.Sleep(500)

// Stop timing
stopwatch.Stop();

Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

Here is a DEMO.


A better way would be to use Stopwatch, instead of DateTime differences.

Stopwatch Class - Microsoft Docs

Provides a set of methods and properties that you can use to accurately measure elapsed time.

// create and start a Stopwatch instance
Stopwatch stopwatch = Stopwatch.StartNew(); 

// replace with your sample code:
System.Threading.Thread.Sleep(500);

stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);