测量代码执行时间 [英] Measuring code execution time
问题描述
为了测试目的,我想知道完成一个过程/函数/命令需要多长时间.
这就是我所做的,但我的方法是错误的,因为如果秒差为 0,则无法返回经过的毫秒数:
注意 sleep 值为 500 ms,所以经过的秒数为 0,则它不能返回毫秒.
Dim Execution_Start As System.DateTime = System.DateTime.NowThreading.Thread.Sleep(500)Dim Execution_End As System.DateTime = System.DateTime.NowMsgBox(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 StopwatchExecution_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 &_女士:"&Execution_Start.Elapsed.Milliseconds &vbNewLine, _"代码执行时间", MessageBoxButtons.OK, MessageBoxIcon.Information)
更好的方法是使用 Stopwatch,而不是 DateTime
差异.
秒表类 - Microsoft Docs><块引用>
提供一组方法和属性,您可以使用它们准确测量经过的时间.
//创建并启动一个秒表实例秒表 秒表 = Stopwatch.StartNew();//替换为您的示例代码:System.Threading.Thread.Sleep(500);秒表.停止();Console.WriteLine(秒表.ElapsedMilliseconds);
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:
Notice the sleep value is 500 ms so elapsed seconds is 0 then it can't return milliseconds.
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
?
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)
A better way would be to use Stopwatch, instead of DateTime
differences.
Stopwatch Class - Microsoft Docs
Provides a set of methods and properties that you can use to accurately 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);
这篇关于测量代码执行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!