Heim  >  Artikel  >  Backend-Entwicklung  >  C#使用记秒表检查程序运行时间

C#使用记秒表检查程序运行时间

大家讲道理
大家讲道理Original
2016-11-10 10:08:001632Durchsuche

如果你担忧某些代码非常耗费时间,可以用StopWatch来检查这段代码消耗的时间,如下面的代码所示

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);

现在已经有专门的工具来检测程序的运行时间,可以细化到每个方法,比如dotNetPerformance软件。

以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。

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

借助于using语法,像下面的代码所示,可以检查一段代码的运行时间,并打印在控制台上。

using (new AutoStopwatch())
{
  Decimal total2 = 0;
  int limit2 = 1000000;
  for (int i = 0; i < limit2; ++i)
  {
     total2 = total2 + (Decimal)Math.Sqrt(i);
  }
}
Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn
Vorheriger Artikel:C#异步方法执行代码Nächster Artikel:C#响应系统配置项的变更