Two ways to measure time in C# .NET
October 20, 2016 Leave a comment
Imagine that you want to want to measure how long it takes to execute a method or function in .NET. Maybe you suspect that a specific call in your code is taking too long but you would like to measure its performance.
There are professional – and expensive – tools out there that can monitor the behaviour of applications at the code level such as AppDynamics or DynaTrace. However, they are relatively complex to install and get to work and may be overkill for a simple initial code diagnostics. Instead you might want to start with some simple C# code to begin with.
DateTime and TimeSpan
Here we register the current UTC date before and after the method execution and then assign their difference to a TimeSpan object. Finally we read the various Total* properties available in TimeSpan, such as TotalSeconds or TotalMilliseconds:
DateTime start = DateTime.UtcNow; Thread.Sleep(2000); DateTime end = DateTime.UtcNow; TimeSpan timeDiff = end - start; Console.WriteLine(Convert.ToInt32(timeDiff.TotalMilliseconds));
There are other time-related properties available in TimeSpan but don’t confuse them with the properties named Total*. E.g. the Seconds property only returns the seconds part of a date time. E.g. if a method took 5 minutes and 23 seconds to execute then Seconds will return 23 whereas TotalSeconds returns 5 * 60 + 23 = 323.
Stopwatch
The Stopwatch class in the System.Diagnostics namespace works pretty much as a real stopwatch. It can be started, restarted, stopped or reset. Its Elapsed property returns a TimeSpan object where again we can read the total milliseconds or minutes and other time-related measurements:
Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); Thread.Sleep(2000); stopwatch.Stop(); TimeSpan stopwatchElapsed = stopwatch.Elapsed; Console.WriteLine(Convert.ToInt32(stopwatchElapsed.TotalMilliseconds));
View all various C# language feature related posts here.