我想知道一个过程/功能/命令需要花费多少时间来进行测试。这是我所做的,但是我的方法是错误的,因为如果秒的差为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 关注
- 474 浏览
添加回答
举报
0/150
提交
取消