gpt4 book ai didi

c# - 测量代码执行时间

转载 作者:IT王子 更新时间:2023-10-29 03:36:01 24 4
gpt4 key购买 nike

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

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

请注意 sleep 值是 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)

最佳答案

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

Stopwatch Class - Microsoft Docs

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

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

关于c# - 测量代码执行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16376191/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com