【问题标题】:Measuring code execution time测量代码执行时间
【发布时间】:2013-04-28 21:03:02
【问题描述】:

出于测试目的,我想知道一个过程/功能/订单需要多长时间才能完成。

这就是我所做的,但我的方法是错误的,因为如果秒差为 0,则无法返回经过的毫秒数:

请注意,睡眠值为 500 毫秒,因此经过的秒数为 0,因此它无法返回毫秒数。

    Dim Execution_Start As System.DateTime = System.DateTime.Now
    Threading.Thread.Sleep(500)

    Dim Execution_End As System.DateTime = System.DateTime.Now
    MsgBox(String.Format("H:{0} M:{1} S:{2} MS:{3}", _
    DateDiff(DateInterval.Hour, Execution_Start, Execution_End), _
    DateDiff(DateInterval.Minute, Execution_Start, Execution_End), _
    DateDiff(DateInterval.Second, Execution_Start, Execution_End), _
    DateDiff(DateInterval.Second, Execution_Start, Execution_End) * 60))

谁能告诉我一个更好的方法来做到这一点?也许是TimeSpan

解决办法:

Dim Execution_Start As New Stopwatch
Execution_Start.Start()

Threading.Thread.Sleep(500)

MessageBox.Show("H:" & Execution_Start.Elapsed.Hours & vbNewLine & _
       "M:" & Execution_Start.Elapsed.Minutes & vbNewLine & _
       "S:" & Execution_Start.Elapsed.Seconds & vbNewLine & _
       "MS:" & Execution_Start.Elapsed.Milliseconds & vbNewLine, _
       "Code execution time", MessageBoxButtons.OK, MessageBoxIcon.Information)

【问题讨论】:

标签: c# .net vb.net datetime timespan


【解决方案1】:

更好的方法是使用Stopwatch,而不是DateTime 差异。

Stopwatch Class - Microsoft Docs

提供一组可用于 准确测量经过的时间。

// create and start a Stopwatch instance
Stopwatch stopwatch = Stopwatch.StartNew(); 

// replace with your sample code:
System.Threading.Thread.Sleep(500);

stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);

【讨论】:

  • @ElektroHacker,不客气,它更容易使用,而且比 DateTime 更准确:)
  • 请参考github.com/chai-deshpande/LogExec(也可以使用NUGET包nuget.org/packages/LogExec)。这与@soner-gonul 提到的完全相同 - 但是,用法很简洁,并且隐藏了所有样板代码。当您想经常使用它时非常有用。它还使用 Common.Logging,以便您可以与首选的日志记录提供程序集成。
  • @Habib 你能帮我理解为什么 Thread.sleep(500) 是必要的吗?我不能跳过睡眠,这会降低效率吗?
  • @Md.SifatulIslam,没有必要使用Thread.Sleep,它只是作为示例代码来显示延迟......事实上,您应该避免在代码中的任何地方使用Thread.Sleep
  • 但这并没有测量进程时间,所以结果会受到系统上运行的其他进程的影响。
【解决方案2】:

Stopwatch 测量经过的时间。

// Create new stopwatch
Stopwatch stopwatch = new Stopwatch();

// Begin timing
stopwatch.Start();

Threading.Thread.Sleep(500)

// Stop timing
stopwatch.Stop();

Console.WriteLine("Time elapsed: {0}", stopwatch.Elapsed);

这是DEMO

【讨论】:

  • 能否用于每行代码的执行时间?例如:bindingSource.datasource = db.table; // 需要多长时间?
  • @vaheeds 当然。只需在每一行的顶部开始这个Stopwatch 并在每一行之后停止它。请记住,您还需要在每一行之后使用Stopwatch.Reset 来计算。根据您的线路;看看ideone.com/DjR6ba
  • 我对它做了一个小技巧,以使毫秒数超出图片。这样 watch.Elapsed.ToString().Split('.')[0]
  • @Doruk 是的,你可以这样做,或者你可以使用Custom Timespan Format Strings,比如stopwatch.Elapsed.ToString(@"d\.hh\:mm\:ss"),这对我来说似乎更干净。
  • 最佳答案。谢谢!
【解决方案3】:

您可以使用此 Stopwatch 包装器:

public class Benchmark : IDisposable 
{
    private readonly Stopwatch timer = new Stopwatch();
    private readonly string benchmarkName;

    public Benchmark(string benchmarkName)
    {
        this.benchmarkName = benchmarkName;
        timer.Start();
    }

    public void Dispose() 
    {
        timer.Stop();
        Console.WriteLine($"{benchmarkName} {timer.Elapsed}");
    }
}

用法:

using (var bench = new Benchmark($"Insert {n} records:"))
{
    ... your code here
}

输出:

Insert 10 records: 00:00:00.0617594

对于高级场景,可以使用BenchmarkDotNetBenchmark.ItNBench

【讨论】:

  • 谢谢,到目前为止最好的答案
  • 谢谢,正在寻找这样的集中方式。也用 ActionFilter 完成了这个策略。
  • 这不仅是一个很好的答案,而且我也从中学到了一些新东西!干得好芽!
【解决方案4】:

如果你使用 Stopwatch 类,你可以使用 .StartNew() 方法将手表重置为 0。所以你不必调用 .Reset() strong> 后跟 .Start()。 可能会派上用场。

【讨论】:

    【解决方案5】:

    如果您要查找关联线程在应用程序内运行代码所花费的时间。
    您可以使用ProcessThread.UserProcessorTime 属性,您可以在System.Diagnostics 命名空间下获得该属性。

    TimeSpan startTime= Process.GetCurrentProcess().Threads[i].UserProcessorTime; // i being your thread number, make it 0 for main
    //Write your function here
    TimeSpan duration = Process.GetCurrentProcess().Threads[i].UserProcessorTime.Subtract(startTime);
    
    Console.WriteLine($"Time caluclated by CurrentProcess method: {duration.TotalSeconds}"); // This syntax works only with C# 6.0 and above
    

    注意:如果你使用多线程,你可以单独计算每个线程的时间并将其相加计算总时长。

    【讨论】:

      【解决方案6】:

      秒表专为此目的而设计,是在 .NET 中测量执行时间的最佳方法之一。

      var watch = System.Diagnostics.Stopwatch.StartNew();
      /* the code that you want to measure comes here */
      watch.Stop();
      var elapsedMs = watch.ElapsedMilliseconds;
      

      不要使用 DateTimes 来衡量 .NET 中的执行时间。

      【讨论】:

        【解决方案7】:

        VB.NET 中如何使用 Stopwatch 类的示例。

        Dim Stopwatch As New Stopwatch
        
        Stopwatch.Start()
                    ''// Test Code
        Stopwatch.Stop()
        Console.WriteLine(Stopwatch.Elapsed.ToString)
        
        Stopwatch.Restart()            
                   ''// Test Again
        
        Stopwatch.Stop()
        Console.WriteLine(Stopwatch.Elapsed.ToString)
        

        【讨论】:

          猜你喜欢
          • 2013-06-24
          • 2022-01-03
          • 1970-01-01
          • 2011-02-18
          • 1970-01-01
          • 1970-01-01
          • 2012-06-19
          • 2012-05-23
          相关资源
          最近更新 更多