4

I am writing a C code (on Linux) that needs to consume a certain amount of CPU when it's running. I am carrying out an experiment in which I trigger certain actions upon reaching a certain CPU threshold. So, once the Utilization reaches a certain threshold, I need to keep it at that state for say 30 seconds till I complete my experiments. I am monitoring the CPU Utilization using the top command.

So my questions are - 1. How do I increase the CPU Utilization to a given value (in a deterministic way if possible)? 2. Once I get to the threshold, is there a way to keep it at that level for a pre-defined time?

Sample output of top command (the 9th column is CPU used by the 'top' process) - 19304 abcde 16 0 5448 1212 808 R 0.2 0.0 0:00.06 top

Similar to above, I will look at the line in top which shows the utilization of my binary.

Any help would be appreciated. Also, let me know if you need more details.

Thanks!

Edit: The following lines of code allowed me to control CPU Utilization quite well - In the following case, I have 2 options - keep it above 50% and keep it below 50% - After some trial and error, I settled down at the given usleep values.

endwait = clock() + ( seconds * CLOCKS_PER_SEC );
while( clock() < endwait ) {}
if (cpu_utilization > 50)
    usleep(250000); 
else
    usleep(700000);

Hope this helps!

Ranjeet
  • 51
  • 1
  • 5
  • 3
    Use a combination of sleep and a busy loop, sleep, busy loop, sleep, busy loop, etc. etc. to achieve any cpu utilization that you want. – David Heffernan Feb 08 '12 at 21:03
  • While a busy loop will obviously keep the reported CPU utilization at a minimum, you may want to throw some unaligned memory accesses in there in order to keep the CPU busy. – Daniel Kamil Kozar Feb 09 '12 at 00:04

2 Answers2

2

cpuburn is known to make CPU utilization so high that it raise its temperature to its max level. It seems there is no more official website about it, but you can still access to source code with Debian package or googlecode. It's implemented in asm, so you'll have to make some glue in order to interact with it in C.

Coren
  • 5,517
  • 1
  • 21
  • 34
2

Something of this sort should have a constant CPU utilization, in my opinion: md5sum < /dev/urandom

user138645
  • 772
  • 1
  • 7
  • 18
  • Hi there and thank you for providing an answer next to your questions. Are you sure that urandom won't block at certain points because it requests a reseed? It seems to me that simply performing hashes on known data is as efficient, and has less chance of blocking. – Maarten Bodewes Feb 12 '12 at 00:56
  • `/dev/urandom` won't block while `/dev/random` will. However, consuming data from either will diminish the entropy pool and may slow down some operations in the future (e.g. cryptography in ssh/ssl). Hashing `/dev/zero` should give you the same CPU consumption without the additional risks. – Michał Kosmulski Feb 25 '12 at 11:43