我想知道一個過程/功能/命令需要花費多少時間來進行測試。這是我所做的,但是我的方法是錯誤的,因為如果秒的差為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 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 & _ "MS:" & Execution_Start.Elapsed.Milliseconds & vbNewLine, _ "Code execution time", MessageBoxButtons.OK, MessageBoxIcon.Information)
3 回答

慕妹3146593
TA貢獻1820條經驗 獲得超9個贊
更好的方法是使用Stopwatch而不是DateTime差異。
秒表類-Microsoft Docs
提供一組方法和屬性,可用于準確測量經過的時間。
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);

MMMHUHU
TA貢獻1834條經驗 獲得超8個贊
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。
- 3 回答
- 0 關注
- 526 瀏覽
添加回答
舉報
0/150
提交
取消