Android Code Snippet TakeTime

LucaMs

Expert
Licensed User
A way to calculate the time taken by a part of source code (very simple and rarely useful but... I was tired of writing these lines every time).

B4X:
Sub TakeTime
   Dim CurrTimeFormat As String = DateTime.TimeFormat
   DateTime.TimeFormat = "mm:ss:SSS"
   Dim Now As Long = DateTime.Now
   Wait for StopTakeTime
   Now = DateTime.Now - Now
   Log("Elapsed time: " & DateTime.Time(Now))
   DateTime.TimeFormat = CurrTimeFormat
End Sub
Usage:
B4X:
TakeTime

' here the code to test

CallSub(Me, "StopTakeTime")
 

JordiCP

Well-Known Member
Licensed User
I like the idea that no Global Var is needed to store the previous TimeStamp, I also need something similar sometimes
Couldn't resist playing with it :D and made a small variation that calls itself and keeps each call timestamp as a reference for the next.

B4X:
Sub TakeTime(tag As String, isFirstReference As Boolean)
    Dim Now As Long = DateTime.Now
    If isFirstReference Then Log($"Stablishing initial reference time at '${tag}'"$)
    Wait For TakeTime(newTag As String, isFirst As Boolean)      'Waits for itself, pls don't do it in real life
    If Not(isFirst) Then
        Now = DateTime.Now - Now
        Dim CurrTimeFormat As String = DateTime.TimeFormat
        DateTime.TimeFormat = "mm:ss:SSS"
        Log($"Elapsed time between '${tag}' and '${newTag}': ${DateTime.Time(Now)} "$)
        DateTime.TimeFormat = CurrTimeFormat
    End If
    TakeTime(newTag, isFirst) 
End Sub

Sub MeasureElapsedTimeSinceLastCall(tag As String, isFirstReference As Boolean)
    CallSub3(Me, "TakeTime", tag, isFirstReference)
End Sub
Usage example:
B4X:
Sub MeasureTest
    MeasureElapsedTimeSinceLastCall("Start", True)              ' Useful if we call MeasureTest multiple times, and we only want it as a reference point
                                                                                       ' Log: Stablishing initial reference time at 'Start'
    Sleep(500)
    MeasureElapsedTimeSinceLastCall("Sleep_500", False)     ' Log: Elapsed time between 'Start' and 'Sleep_500' is: 00:00:502
    Sleep(2000)
    MeasureElapsedTimeSinceLastCall("Sleep_2000", False)   ' Log: Elapsed time between 'Sleep_500' and 'Sleep_2000' is: 00:02:001
    Sleep(3000)
    MeasureElapsedTimeSinceLastCall("Sleep_3000", False)   ' Log: Elapsed time between 'Sleep_2000' and 'Sleep_3000' is: 00:03:001
End Sub
 

Spavlyuk

Member
Licensed User
Might as well turn it into a class with a "proper" implementation so you don't have to include a true/false param when calling it.
 
Top