Page 1 of 1

ElapsedMillisecond time difference (the safe way).

Posted: Sun Sep 04, 2016 2:12 pm
by Roger Hågensen
If you ever needed to measure the time something took and wanted to use ElapsedMilliseconds, but you where afraid of it wrapping around (or unaware that it can/could) this is the solution.

Now since a few PB releases ago ElapsedMilliseconds was changed from using GetTickCount on Windows to using QPC so wraparound or the signed changing to a negative will take yeas I believe.
But that is no excuse for not doing it the right way, and if you ever use any other time stuff (that is not ElapsedMilliseconds) then you need to use a variant of this code anyway to handle wraparounds.

This is a handy (and easy to use) procedure:

Code: Select all

Threaded start_time.q
Procedure.q Check_Time(reset.i = #False)
  If reset
    start_time = ElapsedMilliseconds()
    ProcedureReturn 0
  EndIf
  ProcedureReturn (ElapsedMilliseconds() - start_time)
EndProcedure

;Example

Check_Time(#True) ;Reset the start time of our variable.

Delay(10)
Debug Check_Time()
Delay(10)
Debug Check_Time()
Delay(10)
Debug Check_Time()

If Check_Time() > 30
  Debug "it has been over 30ms"
Else
  Debug "it has been less than 30ms"
EndIf
Now QPC itself has some overhead and so does calling a procedure, the following is a macro variant but it is a little more complex to use (but also ironically simpler codewise).

Code: Select all

Threaded start_time.q
Macro Start_Time()
    start_time = ElapsedMilliseconds()
EndMacro

Macro Check_Time()
   (ElapsedMilliseconds() - start_time)
EndMacro

;Example

Start_Time() ;Reset the start time of our variable.

Delay(10)
Debug Check_Time()
Delay(10)
Debug Check_Time()
Delay(10)
Debug Check_Time()

If Check_Time() > 30
  Debug "it has been over 30ms"
Else
  Debug "it has been less than 30ms"
EndIf
Which is best? The procedure one is fairly self contained but has some overhead, if you only rarely check (once every few seconds) then that is my suggestion.
If you need to check often (like in a main program loop somewhere, like maybe once a second) then I'd suggest the macro version.

Re: ElapsedMillisecond time difference (the safe way).

Posted: Sun Sep 04, 2016 3:11 pm
by IdeasVacuum
very nice Roger, thanks for sharing.