Title: Creating Processor Friendly Applications
Description: Creating applications that does not monopolizes the processor for its own threads.
Author: Paulo Santos
eMail: pjondevelopment@gmail.com
Environment: VB.NET 2005 (Visual Studio 2005)
Keywords: Application, Threading

Creating Processor Friendly Applications

DISCLAIMER

The Software is provided "AS IS", without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and non-infringement. in no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the software.

Introduction

What IS a processor-friendly application?

Simple put, it's a software that does not monopolizes the processor for its own threads.

Why is it important?

Nowadays we have hundreds, if not thousands, of processes slapping each other for the processor attention.


Our role, as developers, is to create applications that give time to the processor to take care of other threads. This way we grant a better experience to the user when using our software.

What is the impact on my application?

Minimal. If well implemented the impact can be undetectable.

How to implement it?

Usually the most processor hungry parts of any application are loops. No matter what kind.

Take a look at the following code:

Dim i as Integer
For k as Integer = 1 to 10000
    '*
    '* Some processor hungry process.
    '*
    i = i + 1
Next

When the above code runs it usually monopolizes the processor and it will hit 100% of CPU usage.


With a simple line the same code will run with less than 10% of CPU usage. Just take a look below:

Dim i as Integer
For k as Integer = 1 to 10000
    i = i + 1

    '*
    '* Giving the processor a break
    '*
    Thread.Sleep(10)
Next

Time is essential on my application, how can I still do it?

With a single line the processor stress can be greatly manageable. Take a look:

Dim i as Integer
For k as Integer = 1 to 10000
    i = i + 1

    '*
    '* Giving the processor a break
    '*
    If (Rnd() < 0.2) Then
        Thread.Sleep(10)
    End If
Next

We increase the complexity a little bit, but the overall speed won't be affected.