Exact Timings

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
User avatar
Chunjee
Posts: 1402
Joined: 18 Apr 2014, 19:05
Contact:

Re: Exact Timings

Post by Chunjee » 11 May 2021, 15:41

I heard on discord that the default sleep has an accuracy of +/-100ms due to how windows allocates CPU time.

Someone posted this function which is accurate down to '100th of a ms'

Code: Select all

delay(time)
{
    DllCall("QueryPerformanceFrequency", "Int64*", freq)
    DllCall("QueryPerformanceCounter", "Int64*", countatstart)
    ; sleep, % (time - 15)
    
     loop,
    {
        DllCall("QueryPerformanceCounter", "Int64*", countrnow)
        timepassed := ((countrnow - countatstart) / freq )*1000
        if (timepassed > time)
        {
            break
        }
    }
    ; ToolTip, % timepassed, 100, 100, 1
}
User avatar
boiler
Posts: 16772
Joined: 21 Dec 2014, 02:44

Re: Exact Timings

Post by boiler » 11 May 2021, 16:22

Like this:

Code: Select all

#MaxThreadsPerHotkey 2

F1::

	Send {lbutton down}
	delay(10)
	Send {lbutton up}

  $stop := 0
  Loop, 
  { 
	Send {lbutton down}
	delay(1)
	Send {lbutton up}
	delay(1)
    {
      return
    }
  }

F2:: $stop := 1

delay(time)
{
    DllCall("QueryPerformanceFrequency", "Int64*", freq)
    DllCall("QueryPerformanceCounter", "Int64*", countatstart)
    ; sleep, % (time - 15)
    
     loop,
    {
        DllCall("QueryPerformanceCounter", "Int64*", countrnow)
        timepassed := ((countrnow - countatstart) / freq )*1000
        if (timepassed > time)
        {
            break
        }
    }
    ; ToolTip, % timepassed, 100, 100, 1
}

If the timing is that critical, then you probably want to put SetBatchLines -1 at the top of your script to prevent it from sleeping for 10 ms after several lines have executed. See the SetBatchLines help page for more info.
User avatar
boiler
Posts: 16772
Joined: 21 Dec 2014, 02:44

Re: Exact Timings

Post by boiler » 11 May 2021, 18:52

Sorry. I accidentally deleted your if statement. Try this (also added the SetBatchlines statement):

Code: Select all

#MaxThreadsPerHotkey 2
SetBatchLines -1 

F1::

	Send {lbutton down}
	delay(10)
	Send {lbutton up}

  $stop := 0
  Loop, 
  { 
	Send {lbutton down}
	delay(1)
	Send {lbutton up}
	delay(1)  
	if ($stop)
    {
      return
    }
  }

F2:: $stop := 1

delay(time)
{
    DllCall("QueryPerformanceFrequency", "Int64*", freq)
    DllCall("QueryPerformanceCounter", "Int64*", countatstart)
    ; sleep, % (time - 15)
    
     loop,
    {
        DllCall("QueryPerformanceCounter", "Int64*", countrnow)
        timepassed := ((countrnow - countatstart) / freq )*1000
        if (timepassed > time)
        {
            break
        }
    }
    ; ToolTip, % timepassed, 100, 100, 1
}
just me
Posts: 9425
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: Exact Timings

Post by just me » 12 May 2021, 05:47

Post Reply

Return to “Ask for Help (v1)”