asp.net Stopwatch is better than DateTime
Posted on May 2, 2010 by Author
In the continuing pursuit of getting my FLV scrubbing application to work correctly, I came across the need to time part of my code. If you are used to using the DateTime object you might want to try something else. Turns out DateTime is meant for Date and Times, and is pretty useless to use as a stopwatch when timing the performance of lines of code within your application. If you were timing how many seconds or hours it takes for something to complete then DateTime is fine, but if you want to get something in the Milliseconds forget about it.
Thankfully I discovered a new Object called the Stopwatch. Very simple to use, and works perfectly.
Here is an example of how I am using it
Stopwatch stopWatch = new Stopwatch();
// transfer data
context.Response.OutputStream.Write(buffer, 0, count);
count = fs.Read(buffer, 0, buffersize);
//calculate transfer rate
TimeSpan ts = stopWatch.Elapsed;
I tried using DateTime instead of stopWatch and the TimeSpan between the two values would always be zero.
Hope this helps others out who find themselves in the same boat.
No Comments have been submitted