performancecpu-usagecpu-speed

CPU Utilization


Q1. What are best practices for a writing a code that does not consume CPU but still achieve a great performance? The question is very generic. What I seek over here is to list down different practices used for different environments? debugging tips besides process-monitor/task manager

EDIT: I am not speaking of IO bound processes. I am speaking of CPU bound process. But, here I do not want my process to keep on hogging CPU. If i have a 4 core machines and if i run four simple loops within a process, the CPU consumption shoots up to 400% till the application/process is running.

I am seeking here some experience on the topic which everyone would have faced some time or other. e.g. I debugged once an application was hogging CPU on Windows as it was looping continuously to search for a non-existent file.

How can I write my program in a way that two different CPU bound applications run smoothly (give a good response)?

UPDATE: Suggestions:

  1. Write good clean code, then Profile your application and then optimize. (Thanks ted for the tip)

  2. It is easier to rewrite/redesign/refactor code than profiling and fixing it.

  3. Use a profiler to debug your application

  4. Don't use spinlocks for threads with long waits

  5. Algorithm choice

These suggestions go a long way for the beginner to understand the concepts.


Solution

  • First, write good clean code. Do things the simplest way possible. After that, do the following repeatedly until you are satisfied with speed of the program:

    1. Profile its execution.
    2. Find the parts where it is spending the most time.
    3. Speed up those parts.

    Do not fall into the trap of perverting your code up front in the name of optimization.

    Remember Amdhal's Law. You aren't going to get noticeable improvements by speeding up something that is already only consuming 1% of your program's time. You get the best bang for your optimization buck by speeding up the part your program spends the most of its time doing.