15 October, 2009
0 Comments
0 categories
To measure execution time in C#, substract start and end datetime.
public void MeasureTime() { // Capture start time DateTime startDateTime = DateTime.Now; // Do something for 1000ms... Thread.Sleep(1000); // Capture end time DateTime endDateTime = DateTime.Now; // Determine duration TimeSpan duration = endDateTime - startDateTime; // Show duration Console.WriteLine(string.Format("Hours{0} Minutes{1} Seconds {2}, Milliseconds{3}",duration.Hours, duration.Minutes, duration.Seconds,duration.Milliseconds)); }
Tags: C#
Of beter nog, gebruik de stopwatch uit System.Diagnostics:
// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();
// Begin timing
stopwatch.Start();
// Do something
Thread.Sleep(1000);
// Stop timing
stopwatch.Stop();
// Write result
Console.WriteLine(“Time elapsed: {0}”, stopwatch.Elapsed);