Search code examples
performancecpuautoit

Least CPU intensive loop


This loop is very CPU intensive:

While 1
    $msg = GUIGetMsg()
    Switch $msg
        Case $GUI_EVENT_CLOSE
            GUIDelete()
            Exit
        Case $control1
            Func1()
        Case $control2
            Func2()
    EndSwitch
WEnd

This is what I always used. I know there are other ways, but which one is least CPU intensive?


Solution

  • I ran into this problem using a Switch/Case as well. I thought making code tighter and changing to Select/Case would lower CPU usage. What I ultimately did was trap the script in a Do/Until loop.

    This excerpt is from a script which lives in the taskbar and always runs. Users interact by clicking and selecting from the context menu I created. That kicks off a respective function.

    While 1
        Do
            $msg = TrayGetMsg()
        Until $msg <> 0
        Select
            Case $msg = $ItemDeviceModel
                DeviceModel()
            Case $msg = $ItemSerial
                SerialNumber()
            Case $msg = $ExitItem
                Exit
        EndSelect
    WEnd
    

    In this example the script loops in the quick and easy Do/Until (which is waiting for a user to click the application icon). After the loop is broken the Select/Case runs.

    Switch your code with:

    While 1
        Do
            $msg = GUIGetMsg()
        Until $msg <> 0
        Switch $msg
            Case $GUI_EVENT_CLOSE
                GUIDelete()
                Exit
            Case $control1
                Func1()
            Case $control2
                Func2()
        EndSwitch
    WEnd