Jump to content
Sign in to follow this  
nhardel

timer not working correctly

Recommended Posts

I am trying to write a script that keeps accurate time regardless of how long functions take to preform their actions.

I thought this would be pretty straight forward. I use several while loops to keep track of days, hours, mins, and secs. But for some reason it is not working correctly.

Global $day, $hour, $min, $sec
 
$time = TimerInit()
While 1 ;Main Loop
$hour = 0 ;Reset hours
While  $hour <= 23;Loop while hours is less than 24 hours
  $min = 0 ;Reset minutes
  While $min <= 59 ;Loop while minutes is less than 60 minutes
   $sec = 0 ;Reset seconds
   While $sec <= 59 ;Loop while seconds is less than 60 seconds
    $show_sec = $sec
    $dif = TimerDiff($time) ;checks how many milliseconds has passed since timer start
    $sec = int($dif/1000) ;counts the seconds
    sleep(50)   ;cpu sleep
    if $sec <> $Show_Sec then ConsoleWrite($sec&@crlf)
   WEnd ;End Sec Loop
   $time = $time + 60 * 1000 ; add one minute to initial time to keep accuracy
   $min = $min + 1 ;Add 1 minute
   Consolewrite("!Min: "&$min&@crlf)
  WEnd ;End Min Loop
  $hour = $hour + 1 ;Add 1 hour
WEnd ;End Hour loop
$day = $day + 1 ; Add 1 day
WEnd

[autoit]

For the first minute it goes according to plan but after that :D

For some reason it does not reset the sec to 0 after the first minute. I am sure that this is tied to the $time = $time + 60 *1000 I don't believe that I am adding 60 seconds to the ticks from the init time but this is what the autoit examples show on how to add ticks. Any ideas?

Share this post


Link to post
Share on other sites

nhardel,

I am sure that this is tied to the $time = $time + 60 *1000

Correct. Where do you get the idea that adding something to the returned value from TimerInit is acceptable? :D

A quote from one of the Devs:

"You are trying to attach meaning to the return value of TimerInit() that we do not guarantee. The return value of TimerInit() should be treated as an opaque handle. That means the underlying type is irrelevant. If I want to make it a string that's my choice as a developer of AutoIt. All I have to ensure is that TimerDiff() still accepts that data and that TimerDiff() returns the calculated difference. There are no other guarantees about how either function works."

So replace that line with a new TimerInit call and your timer works fine:

;$time = $time + 60 * 1000 ; add one minute to initial time to keep accuracy
$time = TimerInit()

this is what the autoit examples show on how to add ticks

Can you tell us where you saw this as it is certainly not correct - as you can see from the above - and we will need to change it if it can be interpreted as such! :oops:

M23


Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

TimerInit()

Parameters

None.

Return Value

Returns a timestamp number (in milliseconds).

TimerDiff

Parameters

timestamp timestamp returned from a previous call to TimerInit().

Return Value

Returns the time difference (in milliseconds) from a previous call to TimerInit().

Sleep(delay)

Parameters

delay Amount of time to pause (in milliseconds).

Return Value

None.

My own assumption: sleep(5 *1000) == sleep(5000) == sleeping 5 seconds

based on that logic

$time = $time + 60 *1000 should add 60 seconds to the timestamp that TimerInit produced.

The problem with calling the TimerInit again after my 60 seconds elapsed is that the timestamp could be off several hundred milliseconds based on timing of functions outside of the seconds loop. This differenced would exponentially grow until I am out of sync with time by seconds, minutes, hours, and days based on when the application started. Granted this is worse case scenario but a possibility none the less. Perhaps I made a leap too far for what was going on but I feel that my examples easily show how someone could make these assumptions based on of how TimerInit works. I was not aware of the developers comments. Yes, I am aware of "how assumptions make an ass out of, well pretty much me this time" Moving forward How would you go about measuring time regardless of the lapse of time that is not measured while a func is off running doing its thing.

Share this post


Link to post
Share on other sites

nhardel,

Unfortunately you fit the "assumption" definition perfectly - but do not worry, you are by no means the first! :rip:

But you might be the last - as the new Beta has this in the Help file:

Return Value
 
Returns a handle that can be passed to TimerDiff() to calculate the difference in milliseconds.

No mention of units in the return value any more. :oops:

How would you go about measuring time regardless of the lapse of time that is not measured while a func is off running doing its thing

Much the same as you are doing at present - use TimerInit and TimerDiff and convert the difference into HH:MM::SS. Are you finding this does not work for you? :D

M23


Public_Domain.png.2d871819fcb9957cf44f4514551a2935.png Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind

Open spoiler to see my UDFs:

Spoiler

ArrayMultiColSort ---- Sort arrays on multiple columns
ChooseFileFolder ---- Single and multiple selections from specified path treeview listing
Date_Time_Convert -- Easily convert date/time formats, including the language used
ExtMsgBox --------- A highly customisable replacement for MsgBox
GUIExtender -------- Extend and retract multiple sections within a GUI
GUIFrame ---------- Subdivide GUIs into many adjustable frames
GUIListViewEx ------- Insert, delete, move, drag, sort, edit and colour ListView items
GUITreeViewEx ------ Check/clear parent and child checkboxes in a TreeView
Marquee ----------- Scrolling tickertape GUIs
NoFocusLines ------- Remove the dotted focus lines from buttons, sliders, radios and checkboxes
Notify ------------- Small notifications on the edge of the display
Scrollbars ----------Automatically sized scrollbars with a single command
StringSize ---------- Automatically size controls to fit text
Toast -------------- Small GUIs which pop out of the notification area

 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • By argumentum
      I was looking for something like this, in the forum and my HDD. Bad hair day. Anyway,
      Here is the code
      If Not StringInStr($CmdLineRaw, "/ErrorStdOut") Then Exit MsgBox(262144, @ScriptName, "...please run this example from editor.", 3) #include <Date.au3>; for _EstimatedTime() #include <InetConstants.au3>; for _EstimatedTime_Example_2() ;=============================================================================== ; ; Function Name: _EstimatedTime() ; https://www.autoitscript.com/forum/topic/177371-_estimatedtime-calculate-estimated-time-of-completion/ ; Description: calculate estimated time of completion ; Parameter(s): $a - holds the data ; $iCurrentCount - Current count ; $iTotalCount - Total count ; Requirement(s): #include <Date.au3> ; Return Value(s): false on incomplete data for assessment ; Author(s): argumentum ; Note(s): read the comments ; ;=============================================================================== Func _EstimatedTime(ByRef $a, $iCurrentCount = "", $iTotalCount = "") If $iCurrentCount & $iTotalCount = "" Then ; initialize $a = "" Dim $a[12] $a[5] = TimerInit() ; handle for TimerDiff() $a[0] = "00:00:00" $a[1] = "00:00:00" $a[2] = _NowCalc() ; starting date and time $a[3] = "" $a[4] = "0" Else If $iTotalCount = 0 Then Return False If $iCurrentCount > $iTotalCount Then $iCurrentCount = $iTotalCount _TicksToTime(Int(TimerDiff($a[5])), $a[6], $a[7], $a[8]) _TicksToTime(Int((TimerDiff($a[5]) / $iCurrentCount) * ($iTotalCount - $iCurrentCount)), $a[9], $a[10], $a[11]) $a[0] = StringFormat("%02i:%02i:%02i", $a[6], $a[7], $a[8]) ; elapsed time $a[1] = StringFormat("%02i:%02i:%02i", $a[9], $a[10], $a[11]) ; estimated total time $a[3] = _DateAdd("s", Int((TimerDiff($a[5]) / $iCurrentCount) * ($iTotalCount) / 1000), $a[2]) ; estimated date and time of completion $a[4] = Int($iCurrentCount / $iTotalCount * 100) ; percentage done EndIf Return True EndFunc ;==>_EstimatedTime _EstimatedTime_Example_1() Func _EstimatedTime_Example_1() ConsoleWrite(@CRLF & "+ Example 1" & @CRLF) ConsoleWrite("elapsed " & @TAB & "estimated" & @TAB & "starting date time " & @TAB & "estimated date time" & @CRLF) ConsoleWrite(" _NowCalc() = " & _NowCalc() & @CRLF) Local $n, $sec = @SEC, $aETTF ; "Estimated Time To Finish" data holder _EstimatedTime($aETTF) ; called with just the data holder to init. it For $n = 1234 To 1 Step -1 Sleep(1) If $sec <> @SEC Then $sec = @SEC _EstimatedTime($aETTF, 1234 - $n, 1234) ConsoleWrite($aETTF[0] & @TAB & $aETTF[1] & @TAB & $aETTF[2] & @TAB & $aETTF[3] & @TAB & $aETTF[4] & @CRLF) EndIf Next _EstimatedTime($aETTF, 1234 - $n, 1234) ConsoleWrite($aETTF[0] & @TAB & $aETTF[1] & @TAB & $aETTF[2] & @TAB & $aETTF[3] & @TAB & $aETTF[4] & @CRLF) ConsoleWrite(" _NowCalc() = " & _NowCalc() & @CRLF) EndFunc ;==>_EstimatedTime_Example_1 _EstimatedTime_Example_2() Func _EstimatedTime_Example_2() ConsoleWrite(@CRLF & "+ Example 2" & @CRLF) ConsoleWrite("elapsed " & @TAB & "estimated" & @TAB & "starting date time " & @TAB & "estimated date time" & @CRLF) ConsoleWrite(" _NowCalc() = " & _NowCalc() & @CRLF) Local $aETTF ; "Estimated Time To Finish" data holder _EstimatedTime($aETTF) ; called with just the data holder to init. it ; Save the downloaded file to the temporary folder. Local $sFilePath = @MyDocumentsDir & "\tempFile.bin" Local $sLink = "http://downloads.sourceforge.net/project/portableapps/PortableApps.com%20Platform/PortableApps.com_Platform_Setup_12.0.5.paf.exe?r=http%3A%2F%2Fsourceforge.net%2Fdirectory%2Fbusiness-enterprise%2Fos%3Awindows%2Ffreshness%3Arecently-updated%2F&ts=1442615522&use_mirror=iweb" ; Download the file in the background with the selected option of 'force a reload from the remote site.' Local $hDownload = InetGet($sLink, $sFilePath, $INET_FORCERELOAD, $INET_DOWNLOADBACKGROUND) ; Wait for the download to complete by monitoring when the 2nd index value of InetGetInfo returns True. Do Sleep(1000) If _EstimatedTime($aETTF, InetGetInfo($hDownload, $INET_DOWNLOADREAD), InetGetInfo($hDownload, $INET_DOWNLOADSIZE)) Then ConsoleWrite($aETTF[0] & @TAB & $aETTF[1] & @TAB & $aETTF[2] & @TAB & $aETTF[3] & @TAB & $aETTF[4] & @CRLF) Else ConsoleWrite(". ") EndIf Until InetGetInfo($hDownload, $INET_DOWNLOADCOMPLETE) ; Retrieve the number of total bytes received and the filesize. Local $iBytesSize = InetGetInfo($hDownload, $INET_DOWNLOADREAD) Local $iFileSize = FileGetSize($sFilePath) ; Close the handle returned by InetGet. InetClose($hDownload) _EstimatedTime($aETTF, $iBytesSize, $iFileSize) ConsoleWrite($aETTF[0] & @TAB & $aETTF[1] & @TAB & $aETTF[2] & @TAB & $aETTF[3] & @TAB & $aETTF[4] & @CRLF) ConsoleWrite(" _NowCalc() = " & _NowCalc() & @CRLF) ; Display details about the total number of bytes read and the filesize. ConsoleWrite("The total download size: " & $iBytesSize & " - The total filesize: " & $iFileSize & @CRLF) ; Delete the file. FileDelete($sFilePath) EndFunc ;==>_EstimatedTime_Example_2  
    • By Chimp
      Simple and generalpurpose stopwatch function

      the GUI interface is not a "finished product" but a simple example to show how to use the function.
      ; --- simple example of use --- #include <GUIConstantsEx.au3> $Form1_1 = GUICreate("Stopwatch", 170, 70);, 100, 100) $LapsedTime = GUICtrlCreateLabel(" 00:00:00.0", 10, 10, 200, 25) GUICtrlSetTip(-1, "Lapsed time") GUICtrlSetFont(-1, 18) $Button1 = GUICtrlCreateButton("halt/go", 10, 40, 50, 20) ; go / pause GUICtrlSetTip(-1, "Pause/Unpause counting") $Button2 = GUICtrlCreateButton("clear", 60, 40, 50, 20) ; reset GUICtrlSetTip(-1, "Clears counter and stops") $Button3 = GUICtrlCreateButton("restart", 110, 40, 50, 20) ; restart GUICtrlSetTip(-1, "Clears counter and restarts") GUISetState(@SW_SHOW) Stopwatch(2) ; reset to 0 and stops While 1 $x = Int(Stopwatch() / 100) $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE Exit Case $Button1 ; toggle status (go <-> pause) Stopwatch() ; this reads counter and sets @extended according to actual $paused status Stopwatch(@extended) ; if is paused (@extended = 1) then unpause [Stopwatch(1)] ; if is unpaused (@extended = 0) then pause [Stopwatch(0)] Case $Button2 ; reset to 0 and stop counter Stopwatch(2) Case $Button3 ; reset to 0 and restart counter Stopwatch(3) EndSwitch If $x <> Int(Stopwatch() / 100) Then $totsec = Int(Stopwatch() / 1000) ; ms to sec $hr = Int($totsec / 3600) ; hours $mn = Int(($totsec - ($hr * 3600)) / 60) ; minutes $sc = Int(($totsec - ($hr * 3600) - ($mn * 60))) ; seconds $tn = Int((Int(Stopwatch() / 100) - ($hr * 36000) - ($mn * 600) - ($sc * 10))) ; tenths of a second GUICtrlSetData($LapsedTime, " " & StringFormat("%02s", $hr) & ":" & StringFormat("%02s", $mn) & ":" & StringFormat("%02s", $sc) & "." & StringFormat("%01s", $tn)) EndIf WEnd ; --- end of example --- ; #FUNCTION# (snippet) ========================================================================================================== ; Name...........: Stopwatch ; Description ...: returns the number of milliseconds counted (according to actions requests by caller) ; Syntax.........: Stopwatch([$action]) ; Parameters ....: $action: 0 - pause counting ; 1 - resume counting ; 2 - reset counter to 0 and stops ; 3 - reset counter to 0 and start counting ; 4 - (default) just ruturns actual counting value and status (status in @extended) ; ; Return values .: number of milliseconds in counter ; @extended contains paused status (1 or 0) ; 1 if stopwatch is in pause ; 0 if stopwatch is counting ; ; Author ........: Chimp ; Modified.......: ; Remarks .......: ; Related .......: ; Link ..........: ; Example .......: yes ; =============================================================================================================================== Func Stopwatch($ToggleTo = 4) Static Local $Paused = True Static Local $Stopwatch = 0 Static Local $TotalTime = 0 Switch $ToggleTo Case 0 ; pause counter If $Paused Then SetExtended($Paused) ; $Paused status Return $TotalTime ; already paused, just return current $TotalTime Else $TotalTime += TimerDiff($Stopwatch) $Paused = True SetExtended($Paused) Return $TotalTime EndIf Case 1 ; unpause counter If $Paused Then $Stopwatch = TimerInit() $Paused = False SetExtended($Paused) Return $TotalTime Else SetExtended($Paused) Return $TotalTime + TimerDiff($Stopwatch) EndIf Case 2 ; reset to 0 and pause $Paused = True $TotalTime = 0 SetExtended($Paused) Return $TotalTime Case 3 ; reset to 0 and restart $Paused = False $TotalTime = 0 $Stopwatch = TimerInit() SetExtended($Paused) Return $TotalTime Case 4 ; return status SetExtended($Paused) If $Paused Then Return $TotalTime Else Return $TotalTime + TimerDiff($Stopwatch) EndIf EndSwitch EndFunc ;==>Stopwatch P.S.
      If you need a finished stopwatch with a nice gui and more functions, take a look to this one by AZJIO
    • By dersiniar
      Hihi guys several hours messing and i still cat figure out why timer wont reset in my func.
      Func shold loop untill timer difference and then it shold do other things including to reset timer as well.
      Timer otself works good. after 30seconds it goes to next func. it just dosnt reset timer. 
      Func _Start() While 1 If TimerDiff($hTimer) > 30 * 1000 Then ; Wait for 10 secs $hTimer = 0 $hTimer = TimerInit() Sleep(100) _Image() Sleep(100) _actTimer() Sleep(100) Else MouseClick("Left", $aPos6[0], $aPos6[1], 1) MouseClick("Left", $aPos4[0], $aPos4[1], 1) MouseClick("Left", $aPos5[0], $aPos5[1], 1) MouseClick("Left", $aPos7[0], $aPos7[1], 150,0) Sleep(100) EndIf WEnd EndFunc  
    • By mrtgtr
      I want to do something , after wait 2 min and again do same thing
      But I do do not want with sleep, it must be timer 
      How I do this ?
    • By Lecdev
      does anyone know what exactly TimerDiff() is doing with the integer returned by TimerInit() in order to get milliseconds?
       
      Just trying to find out if i can use the integer timerinit() returns in a slightly different way to the norm because it will save me a great deal of effort.
       
      ( hoping to save the integer in a db and query rows where the difference in current time integer is > x where x = whatever the integer needs to be to = y hours )
       
       
×
×
  • Create New...