Calculate "estimated time remaining" from progress

Share your advanced PureBasic knowledge/code with the community.
Inf0Byt3
PureBasic Fanatic
PureBasic Fanatic
Posts: 2236
Joined: Fri Dec 09, 2005 12:15 pm
Location: Elbonia

Calculate "estimated time remaining" from progress

Post by Inf0Byt3 »

Here's a quick code made from various others I found on the forum (i think Trond/AND51). It might not be the best way to get the time, but it works :).

Code: Select all

Procedure.s CalculateEstimatedTime(StartTime.l,Progress.f,HS.s,HP.s,MS.s,MP.s,SS.s,SP.s)
 ;
 ;I needed to make this so it can support on-the-fly translations
 ;See an example below
 ;
 ;NOTE that the time might "jump" because this method uses only the progress
 ;and the time for calculations, and the raport between them is small
 ;
 ;StartTime is the date the action has begun, use Date()
 ;Progress is the actula progress
 ;HS means hour (singular)
 ;HP means hours (plural)
 ;MS means minute (singular)
 ;MP means minutes (plural)
 ;SS means second (singular)
 ;SP means seconds (plural)
 ;
 Protected Total.l = 100
 Protected CurrentPosition.l = Progress
 Protected Elapsed.l = Date() - StartTime
 ;
 If Elapsed = 0
  Elapsed = 1
 EndIf
 Speed = Round(CurrentPosition/Elapsed,#PB_Round_Nearest)
 If Speed = 0
  Speed = 1
 EndIf
 RemainingTime = Round((Total-CurrentPosition)/Speed,#PB_Round_Nearest)
 If RemainingTime < 0
  RemainingTime = 1
 EndIf
 ;
 Seconds = RemainingTime % 60
 Minutes = RemainingTime % (60*60) / 60
 Hours = RemainingTime % (60*60*60) / (60*60) 
 ;
 If Hours <> 0
  If Hours = 1
   TimeString.s + Str(Hours)+" "+HS.s+" "
  Else
   TimeString.s + Str(Hours)+" "+HP.s+" "
  EndIf
 EndIf
 If Minutes <> 0
  If Minutes = 1
   TimeString + Str(Minutes)+" "+MS+" "
  Else
   TimeString + Str(Minutes)+" "+MP+" "
  EndIf
 EndIf
 If Seconds = 1
  TimeString + Str(Seconds)+" "+SS
 Else
  TimeString + Str(Seconds)+" "+SP
 EndIf
 ;
 ProcedureReturn Trim(TimeString)
 ;
EndProcedure

;Example
StartTime = Date()
For Do = 0 To 1023
 Progress.f = Do/1023*100
 Debug CalculateEstimatedTime(StartTime,Progress,"hour","hours","minute","minutes","second","seconds")
 Delay(10)
Next
I hope it will come in handy sometime.
None are more hopelessly enslaved than those who falsely believe they are free. (Goethe)