C# uses stopwatch to check program running time

大家讲道理
Release: 2016-11-10 10:08:00
Original
1632 people have browsed it

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);
Copy after login

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);
   }
}
Copy after login

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);
  }
}
Copy after login
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!