测量代码执行时间

Ele*_*ios 104 .net c# vb.net datetime timespan

我想知道程序/功能/订单需要多长时间才能完成测试.

这是我做的,但我的方法是错误的'因为如果秒的差异为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))
Run Code Online (Sandbox Code Playgroud)

有人能告诉我更好的方法吗?也许有一个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)
Run Code Online (Sandbox Code Playgroud)

Hab*_*bib 212

更好的方法是使用秒表而不是DateTime差异.

秒表类 - MSDN

提供一组方法和属性,可用于准确测量经过的时间.

Stopwatch stopwatch = Stopwatch.StartNew(); //creates and start the instance of Stopwatch
//your sample code
System.Threading.Thread.Sleep(500);
stopwatch.Stop();
Console.WriteLine(stopwatch.ElapsedMilliseconds);
Run Code Online (Sandbox Code Playgroud)

  • @ Md.SifatulIslam,没有必要使用`Thread.Sleep`,它只是作为示例代码来显示延迟....实际上你应该避免在代码中的任何地方使用`Thread.Sleep` (8认同)

Son*_*nül 57

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);
Run Code Online (Sandbox Code Playgroud)

这是一个DEMO.

  • @vaheeds当然.只需在每条线的顶部启动"秒表"并在每条线后停止.请记住,您需要在每一行计算后使用[`Stopwatch.Reset`](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.reset.aspx).根据你的线; 看看http://ideone.com/DjR6ba (2认同)
  • @Doruk是的,你可以这样做,或者你可以使用[自定义Timespan格式字符串](https://msdn.microsoft.com/en-us/library/ee372287(v = vs.110).aspx),如`秒表. Elapsed.ToString(@"d\.hh \:mm \:ss")`这对我来说似乎更干净. (2认同)

Ale*_*gin 41

你可以使用这个秒表包装:

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}");
    }
}
Run Code Online (Sandbox Code Playgroud)

用法:

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

输出:

Insert 10 records: 00:00:00.0617594
Run Code Online (Sandbox Code Playgroud)

对于高级方案,您可以使用Benchmark.ItNBench

  • 谢谢,到目前为止最好的答案 (2认同)
  • 谢谢,正在以集中的方式寻找这样的东西。也用 ActionFilter 完成了这个策略。 (2认同)

Mar*_*ell 12

如果使用秒表类,则可以使用.StartNew()方法将监视重置为0.因此,您不必调用.Reset(),然后调用.Start ().可能会派上用场.


小智 5

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

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

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


Sha*_*ati 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
Run Code Online (Sandbox Code Playgroud)

注意:如果你使用的是多线程,你可以单独计算每个线程的时间,然后相加计算总持续时间。