I am developing a C# program, and i have one function that consumes too much CPU. I would like to know a way to control this by code (not with any external application) and restrict the percentage of CPU usage. For example, if it uses 90% of the CPU usage, to make my app consume only a 20%, even if it becomes slower. It must be done automatically and from within the app. If you provide a class, it would be fantastic.
-
This sounds like a crutch: attacking the symptom rather than problem. Why don't you post what the method is trying to do and ask us for help optimizing the method. – Joel Coehoorn Oct 30 '08 at 18:35
-
1It might be a crutch but I can think of a few applications for this idea such as: A CPU bound background task to crunch numbers, a node in a distributed computing environment of office PCs, an artificial intelligence program to monitor and learn from my usage habits. – Brian Ensink Oct 30 '08 at 19:22
-
1To cap CPU usage at 50%, run it on dual core; for a 25% cap, run it on quad core :D – Alan Oct 30 '08 at 19:51
-
My idea is like Brian Ensink is to have an app running on the background but to limit is way of consuming cycles. Very funny idea that of quad cores – netadictos Oct 31 '08 at 09:53
-
@Coehorn: Attacking the symptom might sound like a crutch, but it certainly how most MDs and most of the pharmaceutical industry work (although irrelevant to programming). – Cecil Has a Name Dec 21 '09 at 16:08
3 Answers
I don't know if you can do that, but you can change the thread priority of the executing thread via the Priority property. You would set that by:
Thread.CurrentThread.Priority = ThreadPriority.Lowest;
Also, I don't think you really want to cap it. If the machine is otherwise idle, you'd like it to get busy on with the task, right? ThreadPriority helps communicate this to the scheduler.

- 1,488
- 11
- 20
-
That will help some, and is about the only way I know of doing it. – Mitchel Sellers Oct 30 '08 at 18:21
-
1I've seen Windows apps being able to precisely cap themselves to ... say 50% of CPU. The error rate was less than 1%. – Andrei Rînea Oct 31 '08 at 00:59
-
And what exactly is the benefit of precise capping? Idle cycles are wasted. – dpurrington Nov 05 '08 at 15:49
You can slow down a loop by calling Thread.Sleep(milliseconds) within the loop. That hands the CPU back to the scheduler.
But 'consuming too much CPU' makes me think you might have more fundamental problems. Is this thread polling and waiting for something else? If so, you should consider the use of Events or some other kernel-based signalling mechanism.

- 39,055
- 11
- 90
- 118
I guess you need to query some kind of OS API to find out how much of the CPU are you consuming and take throttling decisions (like Thread.Sleep) from that on.

- 20,288
- 17
- 117
- 166