C# 测量代码执行时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16376191/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 00:53:13  来源:igfitidea点击:

Measuring code execution time

c#.netvb.netdatetimetimespan

提问by ElektroStudios

I want to know how much time a procedure/function/order takes to finish, for testing purposes.

我想知道一个过程/函数/命令需要多少时间来完成,以进行测试。

This is what I did but my method is wrong 'cause if the difference of seconds is 0 can't return the elapsed milliseconds:

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

Notice the sleep value is 500 ms so elapsed seconds is 0 then it can't return milliseconds.

注意 sleep 值是 500 ms,所以经过的秒数是 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))

Can someone show me a better way to do this? Maybe with a TimeSpan?

有人可以告诉我更好的方法吗?也许用TimeSpan?

The solution:

解决方案:

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)

采纳答案by Habib

A better way would be to use Stopwatch, instead of DateTimedifferences.

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

Stopwatch Class - Microsoft Docs

秒表类 - Microsoft Docs

Provides a set of methods and properties that you can use to accurately measure elapsed time.

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

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

回答by Soner G?nül

Stopwatchmeasures time elapsed.

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

Here is a DEMO.

这是一个DEMO.

回答by ohgodnotanotherone

If you use the Stopwatch class, you can use the .StartNew()method to reset the watch to 0. So you don't have to call .Reset()followed by .Start().Might come in handy.

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

回答by Alex Erygin

You can use this Stopwatch wrapper:

您可以使用此秒表包装器:

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

Usage:

用法:

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

Output:

输出:

Insert 10 records: 00:00:00.0617594

For advanced scenarios, you can use BenchmarkDotNetor Benchmark.Itor NBench

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

回答by Sam

Stopwatch is designed for this purpose and is one of the best way to measure time execution in .NET.

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

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

Do not use DateTimes to measure time execution in .NET.

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

回答by Shailesh Prajapati

If you are looking for the amount of time that the associated thread has spent running code inside the application.
You can use ProcessThread.UserProcessorTimeProperty which you can get under System.Diagnosticsnamespace.

如果您正在寻找关联线程在应用程序内运行代码所花费的时间。
您可以使用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

Note: If you are using multi threads, you can calculate the time of each thread individually and sum it up for calculating the total duration.

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

回答by sawsine

I could not see a vb.net version of how one might use the stopwatch Class so i have provided an example below.

我看不到如何使用秒表类的 vb.net 版本,因此我在下面提供了一个示例。

        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)

I hope this helps anyone who arrived at this question looking for vb.net.

我希望这可以帮助任何到达此问题并寻找 vb.net 的人。