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

来源:这里教程网 时间:2026-02-21 13:01:20 作者:

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

System.Diagnostics.Stopwatch timer = new System.Diagnostics.Stopwatch();
timer.Start();
Decimal total = 0;
int limit = 1000000;
for (int i = 0; i <p>现在已经有专门的工具来检测程序的运行时间,可以细化到每个方法,比如dotNetPerformance软件。</p><p>以上面的代码为例子,您需要直接修改源代码,如果是用来测试程序,则有些不方便。请参考下面的例子。</p><div class="aritcle_card flexRow">
                                                        <div class="artcardd flexRow">
                                                                <a class="aritcle_card_img" href="/ai/1902" title="笔尖Ai写作"><img
                                                                                src="https://www.herecours.com/d/file/efpub/2026/21-21/20260221125205166618.jpg" alt="笔尖Ai写作"  onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
                                                                <div class="aritcle_card_info flexColumn">
                                                                        <a href="/ai/1902" title="笔尖Ai写作">笔尖Ai写作</a>
                                                                        <p>AI智能写作,1000+写作模板,轻松原创,拒绝写作焦虑!一款在线Ai写作生成器</p>
                                                                </div>
                                                                <a href="/ai/1902" title="笔尖Ai写作" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span> </a>
                                                        </div>
                                                </div><pre class="brush:c#;toolbar:false">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 

相关推荐

热文推荐