Monday, September 5, 2011

Stopwatch Class and Handy Static Methods of Enumerable

It's amazing how much there is to discover about .NET Framework! A couple of days ago I came across a neat little class called System.Diagnostics.Stopwatch, which was introduced in .NET 2.0! This class comes in handy when you want to measure how long certain operations​ take to execute. I used to work with endTime - startTime, which yiels a timespan, which than needs to be converted to milliseconds or something:

startTime = DateTime.Now;
// do the  processing
endTime = DateTime.Now;
long msElapsed  = (endTime - startTime).Milliseconds / TimeSpan.TicksPerMillisecond;

The Stopwatch class makes our life a bit easier:

Stopwatch sw = new Stopwatch();
sw.Start();
// do the processing
sw.Stop();
long msElapsed =  sw.ElapsedMilliseconds;

Another handy little thing to know is that the System.Linq.Enumerable class has 3 very useful static methods:

Enumerable.Empty<T>() returns an empty set of class T
Enumerable.Range(int start, int count) returns a range of count integers starting from start
Enumerable.Repeat(TResult element, int count) returns a sequence of count objects of type TResult

Happy coding!

No comments:

Post a Comment