Dim stopWatch As New Stopwatch() Dim ts As TimeSpan stopWatch.Start() '开始计时 for xx as integer=1 to 10000 '此处省略运算代码 if xx mod 100=0 ’运算100次停止计时 stopWatch.Stop() ’取得100次运算时间 ts = stopWatch.Elapsed ‘此处省略计算剩余时间计算代码 ‘重新开始计时 stopWatch.restart() end if next stopWatch.stop() stopWatch=nothing
假设循环次数确定,并且每次循环执行时间相等,那么预测时间才是有效的。 Dim dt As DateTime = DateTime.Now For i = 1 To 10000 ... If i Mod 100 = 99 Then Dim dt1 As DateTime = DateTime.Now Dim ts As New TimeSpan(dt1.Ticks - dt.Ticks) Dim 已经用时间 = ts.TotalSeconds Dim 还需时间 = ts.TotalSeconds / i * (10000 - i) Dim 估计完成时间 = DateTime.Now.AddSeconds(还需时间) End If Next
写一个 VB6 风格的函数:Public Function Get_Remain_Time(ByVal startTime As Date, ByVal currentProgress As Long, ByVal finalProgress As Long) As String Dim meanTime As Double meanTime = (Now - startTime) / currentProgress
Dim stopWatch As New Stopwatch()
Dim ts As TimeSpan
stopWatch.Start() '开始计时
for xx as integer=1 to 10000
'此处省略运算代码 if xx mod 100=0
’运算100次停止计时
stopWatch.Stop() ’取得100次运算时间
ts = stopWatch.Elapsed ‘此处省略计算剩余时间计算代码 ‘重新开始计时
stopWatch.restart()
end if
next
stopWatch.stop()
stopWatch=nothing
Dim dt As DateTime = DateTime.Now
For i = 1 To 10000
...
If i Mod 100 = 99 Then
Dim dt1 As DateTime = DateTime.Now
Dim ts As New TimeSpan(dt1.Ticks - dt.Ticks)
Dim 已经用时间 = ts.TotalSeconds
Dim 还需时间 = ts.TotalSeconds / i * (10000 - i)
Dim 估计完成时间 = DateTime.Now.AddSeconds(还需时间)
End If
Next
Dim meanTime As Double meanTime = (Now - startTime) / currentProgress
Get_Remain_Time = Format(CDate((finalProgress - currentProgress) * meanTime), "HH小时nn分ss秒")
End Function
调用时 Lable1 = Get_Remain_Time(datStartTime, i, 10000),其中 datStartTime 是你记录的开始时间,i 是循环变量。
DoEvents
Label1.Caption = "当前进度:" & Format(i * 100 / 10000, "0.00") & "%" 'do something..............
Next我一般就像上面这样弄个进度就得了。