wgallon
wgallon

Reputation: 57

C# Keep CPU at/near designated percent usage for testing purposes

I am currently working on a little in-house testing app to create multiple types of load on the computer so that we can see how our software works under load. I am getting hung up on one request, in that I make some sort of way to specify a percent usage of the CPU (say, 40%) before the user runs the program, and that will hopefully keep the cpu in a range +-10% of what they put in. I've been told that they had seen programs doing it before, but every one that I had seen that claimed to do so did not work. I am attempting to read an average usage and sleep the thread running so that the CPU usage lowers, but I have found that is not accurate. It is also going to be used on multiple servers, each with different CPUs, so I can't do very much hard coding as it will need to work on each server. I personally do not think its possible to accurately do, but I'm asking here as a last ditch effort to see if anyone else has come across software similar to this, and knows how it would be written.

Edit: I have attempted to use a lower priority thread, and was also told that would not be useful to them (though I had the option created just for the purpose of testing before this was requested of me).

Upvotes: 5

Views: 584

Answers (2)

usr
usr

Reputation: 171178

Starting with Windows 8 you can make the OS scheduler cap the CPU usage using Windows Jobs.

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

We did something analogous a while back tuning an application server. We found that our overall throughput was best when the CPU was around 70%. Our solution was to spin up additional threads, with a delay between each one, until the desired load was reached. If CPU went above 80%, we reduced the number of running threads (signaled a thread to finish its current work and then terminate). If CPU dropped below 60%, we fired up a new thread.

You could apply similar logic to create artificial load that you can tune to a target CPU utilization. Your threads would need to balance CPU and non-CPU (IO, or just sleep) in order to allow for fine tuning. If your threads are very CPU intensive, each will consume 1 CPU core to about 100%.

Upvotes: 3

Related Questions