【问题标题】:AHK loop High CPU UsageAHK 循环 CPU 使用率过高
【发布时间】:2020-08-26 20:37:04
【问题描述】:

我正在运行一个自动大写句子的第一个字符的 Autohotkey 脚本(例如在 Texstudio 或 Chrome 中)。脚本(特别是我猜的循环)有时会占用 30-40% 的 CPU。因此,我想知道是否有可能优化代码(也许不使用循环?)以减少 CPU 使用率。提前致谢。代码如下:

#SingleInstance force
#NoEnv
SetBatchLines -1

Loop {
if WinActive("ahk_exe texstudio.exe") or WinActive("ahk_exe chrome.exe")
Input key, I L1 M V,{Esc}{BS}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Tab}
StringUpper key, key

If InStr(ErrorLevel,"EndKey")

state =

Else If InStr(".!?",key)

state = 1

Else If InStr("`t `n",key) {

If state = 1

state = 2

} Else {

If state = 2

Send {BS}{%key%}

state =

}

}

Return 

【问题讨论】:

    标签: loops cpu autohotkey


    【解决方案1】:

    SetTimer 因为周期而消耗的 CPU 更少。

    #SingleInstance force
    #NoEnv
    #Persistent
    ; SetBatchLines -1
    
    ; create a group of the programs in which you want auto-capitalize
    GroupAdd, auto_capitalize_group, ahk_exe texstudio.exe
    GroupAdd, auto_capitalize_group, ahk_exe chrome.exe
    
    SetTimer, auto_capitalize, 300 ; check every 300 ms
    Return 
    
    auto_capitalize: 
    if !WinActive("ahk_group auto_capitalize_group")
        return  ; do nothing
    ; otherwise:
    Input key, I L1 M V,{Esc}{BS}{Left}{Right}{Up}{Down}{Home}{End}{PgUp}{PgDn}{Tab}
    StringUpper key, key
    If InStr(ErrorLevel,"EndKey")
        state =
    Else If InStr(".!?",key)
        state = 1
    Else If InStr("`t `n",key) 
    {
        If state = 1
            state = 2
    } 
    Else 
    {
        If state = 2
            Send {BS}{%key%}
        state =
    }
    Return
    

    【讨论】:

    • 你觉得如果Sleep, 300和SetTimer的性能一样吗?
    • @DagicCross,使用 SetTimer 的主要优点是您可以添加额外的东西(热键、hotstsrings、函数、其他计时器等),而无需使用可能相互干扰的其他脚本。
    猜你喜欢
    • 2018-09-07
    • 1970-01-01
    • 1970-01-01
    • 2019-02-22
    • 2020-01-21
    • 2020-09-27
    • 2023-03-10
    • 2021-12-09
    • 2014-07-16
    相关资源
    最近更新 更多