Stopwatch time calculation program running

Sometimes we want to know a code segment, or time a method of execution. The general practice is to create one before you begin DateTime variable recording the current time, and then back at the end of the implementation to create a DateTime variable recording the current time. Thus the two time a Save i.e. the time difference can be obtained a TimeSpan variable. No problem doing this, so if I want to calculate the execution time of a lot of code segments of it? According to this method, I want to create a lot of DateTime variable, of course, you will say can be used directly DateTime.Now , without creating a new DateTime variables, however, such an approach are too cumbersome. .NET provides a class - Stopwatch for timing. You only need to use its Start method, the timing of when you need it, and in the end is timed to call Stop method just fine. It will be property Elapsed to return time interval. Really good on tall!

 

Do not use Stopwatch:

DateTime dt1 = DateTime.Now;

//execute .....

DateTime dt2 = DateTime.Now;

//execute .....

TimeSpan ts = (DateTime.Now -dt2) + (dt2 - td1);

 

Use Stopwatch

Stopwatch sw = new Stopwatch();

sw.Start();

//execute ....

sw.Stop();

//......

sw.Start();

//execute....

sw.Stop();

//You can use sw.Elapsed or other properties

 

 

 

Published 55 original articles · won praise 39 · views 80000 +

Guess you like

Origin blog.csdn.net/Chinese521/article/details/38372825