asp.net Stopwatch is better than DateTime


asp.net Stopwatch is better than DateTime

Posted on May 2, 2010 by Paul White

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();
stopWatch.Start();
                       
// transfer data
context.Response.OutputStream.Write(buffer, 0, count);
context.Response.Flush();
count = fs.Read(buffer, 0, buffersize);
                       
stopWatch.Stop();
                       
//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.

Permalink
2835 Visitors
6215 Views

Categories associated with asp.net Stopwatch is better than DateTime

Discussion

No Comments have been submitted
name
Email Needed to confirm comment, but not made public.
Website
 
Type Code
Security Check
 
When you Post your Comment, you'll be sent a confirmation link. Once you click this link your thoughts will be made public.. Posts that are considered spam will be deleted, Please keep your thoughts and links relavent to this Article