11 June 2016

Calculating difference between start and end time

When you want know measure how long it takes to a web service method to return response in test/production environment, what you will do?

The easiest way is to keep calculate the difference between current date time before calling the method and after calling the method. Some thing like below:

DateTime start = DateTime.Now;
 
// Call web service
            
DateTime end = DateTime.Now;
TimeSpan difference = end.Subtract(start);

But there is a better way available in the form of Stopwatch class present in System.Diagnostics namespace starting from .NET Framework 2.0 version.

Stopwatch watcher = new Stopwatch();
watcher.Start();

// Call web service

watcher.Stop();

The Stopwatch object gives Elapsed TimeSpan property, which gives the time difference between starting and stopping the watcher. Also there is more handy property named "ElapsedMiliseconds" which gives Elapsed time in millisecond.

TimeSpan difference = watcher.Elapsed;

long durationInMillisecond = watcher.ElapsedMilliseconds;

No comments:

Post a Comment