ElapsedMillisecond time difference (the safe way).

Share your advanced PureBasic knowledge/code with the community.
User avatar
Roger Hågensen
User
User
Posts: 47
Joined: Wed Mar 25, 2015 1:06 pm
Location: Norway

ElapsedMillisecond time difference (the safe way).

Post 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.
4 music albums under CC BY license available for free (any use, even commercial) at Skuldwyrm.no
IdeasVacuum
Always Here
Always Here
Posts: 6426
Joined: Fri Oct 23, 2009 2:33 am
Location: Wales, UK
Contact:

Re: ElapsedMillisecond time difference (the safe way).

Post by IdeasVacuum »

very nice Roger, thanks for sharing.
IdeasVacuum
If it sounds simple, you have not grasped the complexity.
Post Reply