Search

Measure execution time

This C# code snippet measures a time interval as you would measure the execution time of a task.
using System;

DateTime startTime = DateTime.Now;
Console.WriteLine ("Started: {0}", startTime);
 
// Execute the task to be timed
for (int i=1; i < 100000; i++){}   
  
DateTime stopTime = DateTime.Now;
Console.WriteLine ("Stopped: {0}", stopTime);
 
TimeSpan elapsedTime = stopTime - startTime;
Console.WriteLine ("Elapsed: {0}", elapsedTime);
Console.WriteLine ("in hours       :" + elapsedTime.TotalHours);
Console.WriteLine ("in minutes     :" + elapsedTime.TotalMinutes);
Console.WriteLine ("in seconds     :" + elapsedTime.TotalSeconds);
Console.WriteLine ("in milliseconds:" + elapsedTime.TotalMilliseconds);