Home  >  Article  >  Backend Development  >  C# uses stopwatch to check program running time

C# uses stopwatch to check program running time

大家讲道理
大家讲道理Original
2016-11-10 10:08:001634browse

If you are worried that some code is very time-consuming, you can use StopWatch to check the time consumed by this code, as shown in the code below

System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
Decimal total = 0;
int limit = 1000000;
for (int i = 0; i < limit; ++i)
{
  total = total + (Decimal)Math.Sqrt(i);
}
timer.Stop();
Console.WriteLine(“Sum of sqrts: {0}”,total);
Console.WriteLine(“Elapsed milliseconds: {0}”,
timer.ElapsedMilliseconds);
Console.WriteLine(“Elapsed time: {0}”, timer.Elapsed);

There are now special tools to detect the running time of the program, which can be refined down to each step. A method, such as dotNetPerformance software.

Taking the above code as an example, you need to modify the source code directly, which is a bit inconvenient if it is used to test the program. Please refer to the example below.

class AutoStopwatch : System.Diagnostics.Stopwatch, IDisposable
{
   public AutoStopwatch()
   { 
     Start();
   }
   public void Dispose()
   {
     Stop();
     Console.WriteLine(“Elapsed: {0}”, this.Elapsed);
   }
}

With the help of using syntax, as shown in the code below, you can check the running time of a piece of code and print it on the console.

using (new AutoStopwatch())
{
  Decimal total2 = 0;
  int limit2 = 1000000;
  for (int i = 0; i < limit2; ++i)
  {
     total2 = total2 + (Decimal)Math.Sqrt(i);
  }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn