Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 825
Levi Avatar asked Sep 27 '13 03:09

Levi


People also ask

Why are busy loops inefficient?

Problems With Busy Waiting In some operating systems, busy waiting can be inefficient because the looping procedure is a waste of computer resources. In addition, the system is left idle while waiting. This is particularly wasteful if the task/process at hand is of low priority.

What is a CPU intensive process?

Compute-Intensive (or CPU-Intensive) Processes Compute-intensive processes are ones that perform IO rarely, perhaps to read in some initial data from a file, for example, and then spend long periods processing the data before producing the result at the end, which requires minimal output.

What makes an application CPU intensive?

So what are CPU Intensive tasks? They are complex user actions that eat up more RAM. A few of such processes can shut down your server entirely. Naturally, you want to make sure that your app or website is 'smart' enough to handle different kinds of tasks, for each individual user request.


1 Answers

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
like image 167
Colyn1337 Avatar answered Sep 24 '22 22:09

Colyn1337