How to optimize the speed of a script as much as possible.

Helpful script writing tricks and HowTo's
dsewq1LYJ
Posts: 116
Joined: 26 Aug 2014, 23:21

Re: How to optimize the speed of a script as much as possible.

24 Sep 2015, 08:13

WAZAAAAA wrote:
dsewq1LYJ wrote:Higher precision but higher usage ?
And may I ask.
What's the lowest delay of the function
According to my benchmarks:
Sleep default method = low CPU, low precision
Sleep suspend method = low CPU, high precision, issues with SetTimer
Sleep precise method = high CPU, higher precision
But sometimes when using the precise method, it eats so much CPU that it actually ends up slowing everything down, this has happened to a friend of mine too with a weaker PC, that's why I have replaced it with the suspend mode.
You can read more about precise sleeps at RHCP's thread: http://www.autohotkey.com/board/topic/9 ... -function/

I don't understand what do you mean with lowest delay.
May I ask.What's the situation when Ternary faster than Genreral If condition ?
ozzii
Posts: 481
Joined: 30 Oct 2013, 06:04

Re: How to optimize the speed of a script as much as possible.

25 Sep 2015, 02:07

I don't know why it's faster (or if it is), it's not me who gave that statement.

But the number of parameters don't do things slower, at least I think so.
User avatar
jNizM
Posts: 3183
Joined: 30 Sep 2013, 01:33
Contact:

Re: How to optimize the speed of a script as much as possible.

25 Sep 2015, 03:26

Ternary vs if/else (Short)

Code: Select all

Ternarry:        2.828439
if/else:         3.931492
Code:
Spoiler

Ternary vs if/else (Big)

Code: Select all

Ternarry:        tba...
if/else:         tba...
Spoiler
[AHK] v2.0.5 | [WIN] 11 Pro (Version 22H2) | [GitHub] Profile
dsewq1LYJ
Posts: 116
Joined: 26 Aug 2014, 23:21

Re: How to optimize the speed of a script as much as possible.

20 Oct 2015, 08:16

jNizM wrote:Ternary vs if/else (Short)

Code: Select all

Ternarry:        2.828439
if/else:         3.931492
Code:
Spoiler

Ternary vs if/else (Big)

Code: Select all

Ternarry:        tba...
if/else:         tba...
Spoiler
Can not wait anymore for the final result :D

Thank you so much!
dsewq1LYJ
Posts: 116
Joined: 26 Aug 2014, 23:21

Re: How to optimize the speed of a script as much as possible.

21 Oct 2015, 04:03

Can someone test follow code for me...

I got bad PC and I am a student, I cant use Computer all day (even just place it and wait for it to finish)

Code: Select all

SetBatchLines -1
 
global lcnt := 100000

WinAct(ttl)
{
	WinActivate % ttl
}

; ===============================================================================================================================
 
QPC(1)
 
Loop % lcnt
{
	WinActivate ahk_class Chrome_WidgetWin_1
}
test1 := QPC(0)
 
; ===================================================================================
 
QPC(1)
 
loop % lcnt
{
	WinAct("ahk_class Chrome_WidgetWin_1")
}
test2 := QPC(0)
 
; ===================================================================================
 
MsgBox % test1 "`n" test2
ExitApp
 
; ===============================================================================================================================
 
QPC(R := 0)
{
    static P := 0, F := 0, Q := DllCall("QueryPerformanceFrequency", "Int64P", F)
    return !DllCall("QueryPerformanceCounter", "Int64P", Q) + (R ? (P := Q) / F : (Q - P) / F) 
}
-------------------
Edit the title to whatever you want.

Any help I'll appreciate it :D
just me
Posts: 9406
Joined: 02 Oct 2013, 08:51
Location: Germany

Re: How to optimize the speed of a script as much as possible.

21 Oct 2015, 06:58

You might want to look at SetWinDelay.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: How to optimize the speed of a script as much as possible.

26 Mar 2016, 06:27

*bump

I am prepare atm my post in the forum - its a bit complitcated. But i dont wanna post wrong things.

So we have the general performance settings, which can use in most cases without troubleshooting

Code: Select all

;************************************************
;Performance PARAMETERS
;************************************************
#NoEnv
Process, Priority, , H
SetBatchLines, -1
ListLines Off
#KeyHistory 0
SendMode Input
SetTitleMatchMode 2
SetTitleMatchMode Fast
SetKeyDelay, -1, -1, Play
SetMouseDelay, -1
SetWinDelay, 0		
SetControlDelay, 0	
SetDefaultMouseSpeed, 0


All possible Performance Parameters with short Description

Code: Select all

;************************************************
;PERFORMANCE PARAMETERS DESCRITPION
;************************************************
/*
#MaxHotkeysPerInterval 99000000	:default 70  	- prevent creating endless loops
#HotkeyInterval 99000000		;default 2000 	- Hoy much hotkeys can activate per ms
#KeyHistory 0					;disable KeyHistory log

Process, Priority, , L ;if unstable, comment or remove this line

#MaxThreads 255				;default 10 	- How many Hotkeys + Timers .. can run simultanously 
#MaxMem 4095					;default 64MB - Max 4095	 set the Memory use for each Variable 
#MaxThreadsBuffer On			;default Off - This is the default behavior. A hotkey press will be ignored whenever that hotkey is already running its maximum number of threads (usually 1, but this can be changed with #MaxThreadsPerHotkey).

ListLines,  Off					
;ListLines Off/On can be used to selectively omit some lines from the history, which can help prevent the history from filling up too quickly (such as in a loop with many fast iterations). ListLines Off may also improve performance by a few percent.

SetBatchLines, -1
;default 10 -  
;SetBatchLines is set to 10 ms (the default), a task that uses 20 ms of CPU time will run for ~10 ms, sleep to allow other processes to run, and then run for the final 10 ms. If SetBatchLines is set to 2 ms, a task that uses 20 ms of CPU will sleep ~10 times before completing.

My advice... Leave SetBatchLines at the default of 10 ms. 10 ms is a good default. Most scripts run fine with this setting. If needed, increase SetBatchLines to a higher value (20ms, 50ms, -1, etc.) if one or more of your tasks needs more priority.

;SetBatchLines, 10ms  - 
;SetBatchLines, 1000

SetTitleMatchMode fast
;Fast: This is the default behavior. Performance may be substantially better than Slow, but certain WinText elements for some types of windows may not be "seen" by the various window commands.
;The built-in variables A_TitleMatchMode and A_TitleMatchModeSpeed contain the current settings.


SetKeyDelay, -1, -1
; default 10 - Sets the delay that will occur after each keystroke sent by Send and ControlSend. -1 
;Use -1 for no delay at all and 0 for the smallest possible delay 

SetMouseDelay, -1 
;Sets the delay that will occur after each mouse movement or click.
;
;default 10 - Sets the delay that will occur after each mouse movement or click.

SetDefaultMouseSpeed, 0
SetWinDelay, -1
SetControlDelay, -1
SendMode Input	; Recommended for new scripts due to its superior speed and reliability.

*/
SvenBent
Posts: 266
Joined: 09 Aug 2015, 01:34

Re: How to optimize the speed of a script as much as possible.

26 Mar 2016, 14:34

May i put in a small warning against "Process, Priority, , H" especially for big CPU heavy scripts

Process, Priority, , H puts you priority in the group with keyboard input and network drivers. So any CPU heavy sections of the script is going to infuse lag on both KB and network.
However if you script does not have any CPU heavy.sections there is no real benefit from adjusting priory. may i instead suggest do do only "Process, Priority, , A" it will still keep you priority above any other running software but below network and keyboard. Since Windows priority model is blocking priority ( With a lot of exceptions) there is no difference from being in High vs Above, when all other software is in Normal anyway. ( aka multiple steps higher priority is just as good as one step higher)

in short: unless you have a very specific technically reason. use only "Process, Priority, , A" to increase script priority.
SvenBent
Posts: 266
Joined: 09 Aug 2015, 01:34

Re: How to optimize the speed of a script as much as possible.

26 Mar 2016, 15:29

a little tip

Avoid spreading math over multiple lines and using variable for intermediate results if they are only used once.
As much as possible condense math into one line and only use variables for storing math results if you need the results being used multiple times later.

remember that:
1x calc < 1x calc + 1x memory read < 2x calc


Code: Select all

#NoEnv  ; Recommended for performance and compatibility with future AutoHotkey releases.
SendMode Input  ; Recommended for new scripts due to its superior speed and reliability.
SetWorkingDir %A_ScriptDir%  ; Ensures a consistent starting directory.

#Singleinstance force
SetBatchlines, -1
ListLines Off
#KeyHistory 0

var_Input1:=123
var_Input2:=456


start:=A_tickcount
Loop 99999999
	{
	X:= (2 * var_Input1 ) -1
	Y:= (3 / var_Input2 ) +7
	Z:= X / Y
	}
Results1:=A_tickcount - start


start:=A_tickcount
Loop 99999999
	{
	Z:= ((2 * var_Input1 ) -1) / ((3 / var_Input2 ) +7)
	}
Results2:= A_tickcount - start


msgbox %Results1% - %Results2%
The second condensed method is slightly more than 50% faster
Last edited by SvenBent on 28 Mar 2016, 00:05, edited 1 time in total.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: How to optimize the speed of a script as much as possible.

26 Mar 2016, 17:16

do a function and the lines in it count as one operation or count the lines inside the function for the memory handling. Those things really make sense in script with a high calculating processes.

I have more the problem to reduce now the Speed from a script , because i get stutters. I integrate this inside the help post, what is atm in under construction. (FastimageSearch is fast but have some little problems)
SvenBent
Posts: 266
Joined: 09 Aug 2015, 01:34

Re: How to optimize the speed of a script as much as possible.

27 Mar 2016, 01:31

HinkerLoden wrote:do a function and the lines in it count as one operation or count the lines inside the function for the memory handling. Those things really make sense in script with a high calculating processes.

I have more the problem to reduce now the Speed from a script , because i get stutters. I integrate this inside the help post, what is atm in under construction. (FastimageSearch is fast but have some little problems)
I'm sorry I'm not getting what you are trying to say. Is the first line a question or a statement ?
If your AHK script is making other software stutter, then Tty to reduce the priority to BelowNormal. Having CPU heavy stuff run in High or Realtime is a perfect way to make a computer unresponsive.
User avatar
HinkerLoden
Posts: 93
Joined: 23 Mar 2016, 07:50
Contact:

Re: How to optimize the speed of a script as much as possible.

27 Mar 2016, 04:14

a function count as one operation process or each line inside the function ?
User avatar
boiler
Posts: 16705
Joined: 21 Dec 2014, 02:44

Re: How to optimize the speed of a script as much as possible.

27 Mar 2016, 13:32

If you are asking if calling a function only takes the processing time of one typical line of code rather than the time it takes to execute all of the lines inside the function, the answer is that it takes the time to execute all of the lines of code inside the function. There's nothing magical about putting lines of code inside a function that makes them free. It still takes CPU time to do stuff.
User avatar
SnowFlake
Posts: 368
Joined: 28 Apr 2015, 05:41
Contact:

Re: How to optimize the speed of a script as much as possible.

01 Apr 2016, 13:51

any examples on how
PixelSearch,,,1,1,1,1,0xEEEEEE
is faster?
:yawn:
SvenBent
Posts: 266
Joined: 09 Aug 2015, 01:34

Re: How to optimize the speed of a script as much as possible.

01 Apr 2016, 18:10

T His is probably way down into miniscule area but
Using Gosub seems to be 25% faster than using a function.
User avatar
WAZAAAAA
Posts: 88
Joined: 13 Jan 2015, 19:48

Re: How to optimize the speed of a script as much as possible.

05 Apr 2016, 07:30

SnowFlake wrote:any examples on how
PixelSearch,,,1,1,1,1,0xEEEEEE
is faster?
More information on point 10 from the first post.
Otherwise try this benchmark yourself:

Code: Select all

#NoEnv
#SingleInstance Force
#MaxHotkeysPerInterval 99000000
#HotkeyInterval 99000000
#KeyHistory 0
ListLines Off
Process, Priority, , A
SetBatchLines, -1
SetKeyDelay, -1, -1
SetMouseDelay, -1
SetDefaultMouseSpeed, 0
SetWinDelay, -1
SetControlDelay, -1
SendMode Input

DllCall("QueryPerformanceFrequency", "Int64*", Frequency)
StartTime := A_TickCount
DllCall("QueryPerformanceCounter", "Int64*", CounterBefore)
loop 500000
{
	PixelSearch,,,1,1,1,1,0xEEEEEE,,Fast
	if errorlevel = 0
	Sleep -1
}
DllCall("QueryPerformanceCounter", "Int64*", CounterAfter)
ElapsedTime := A_TickCount - StartTime
MsgBox % "TickCount:`n" ElapsedTime " ms`n`n" "QueryPerformanceCounter:`n" . (CounterAfter - CounterBefore)*1000/Frequency . " ms"
PixelSearch,,,1,1,1,1,0xEEEEEE looped for 500000 times took me 3,3 seconds
PixelSearch,,,1,1,1,1,0xEEEEEE,,Fast looped for 500000 times took me 8,1 seconds
(tested with V-Sync OFF on Windows which appears to loop much much faster)
Last edited by WAZAAAAA on 31 Oct 2016, 20:39, edited 2 times in total.
YOU'RE NOT ALEXANDER
SvenBent
Posts: 266
Joined: 09 Aug 2015, 01:34

Re: How to optimize the speed of a script as much as possible.

19 May 2016, 09:28

Another miniscule speed tip

Replacing

Code: Select all

    DllCall("SetProcessWorkingSetSize", Int,-1, Int,-1, Int,-1 )
with

Code: Select all

    return, dllcall("psapi.dll\EmptyWorkingSet", "UInt", -1)
You get around a 27% speedup on that emptymem call


also Doing Loop with a set value instead of a variable is 1.2% faster
Further investigation seems to deny this
SvenBent
Posts: 266
Joined: 09 Aug 2015, 01:34

Re: How to optimize the speed of a script as much as possible.

20 May 2016, 15:38

a few tips for IF checking of Boolean values
Tested on a Core2Quad Q6600 system.


if VariableName
Seems to be the fastest way to check if a variable is True


if VariableName = 0
Is the fastest way to check if a variable is false however it does not take into account of the variable is not set, aka empty. The IF commands does not get activaged if the variable is not set/empty

if VariableName <> 1
is almost as fast and an empty variable is considere false ( aka the IF settings get activated) just like if it contained a 0

if Not VariableName
Seems to be slower than both of the two above
User avatar
rootmos
Posts: 35
Joined: 11 Mar 2016, 04:38
Location: Sweden
Contact:

Re: How to optimize the speed of a script as much as possible.

31 May 2016, 15:37

This is awesome! Thanks for sharing! :)
Look at me, I am your god now.
User avatar
WAZAAAAA
Posts: 88
Joined: 13 Jan 2015, 19:48

Re: How to optimize the speed of a script as much as possible.

27 Oct 2016, 07:02

- added various inputs from various users (thanks to jNizM, dd900, SvenBent)
- changed Priority from H to A under SvenBent's recommendation. I used H initially because I was under the seemingly wrong impression that "Above Normal" wasn't supported in every Windows operating system
- modified benchmark script, which is now shorter and slightly more precise
- slightly changed RegEx code
- minor fixes here and there
YOU'RE NOT ALEXANDER

Return to “Tutorials (v1)”

Who is online

Users browsing this forum: No registered users and 28 guests