I want to increase my CPU usage through a java program, albeit in a controlled manner. Say, a user can specify a parameter like “high”, “medium” or “low” and I should be able to increase the CPU by a certain amount depending on the user’s choice. Lets say for high I want it to increase by 5%, for medium by 3% and for low by 1%.
Is this possible with a clean and efficient method (not just using while and for loops)? IF yes, then how and what will be the precision and accuracy?
Thanks in advance
You can modify the CPU load incurred by a Java program by inserting sleep statements (e.g.
Thread.sleep()) in your code, using variable delays to change the load. The simplest case would be a sleep statement in a loop, executed in a separate thread for each CPU core that you want to load.That said, Java is not suitable for this task – not if you actually need the kind of precision that you are describing. The garbage collector and other factors make its behavior rather unpredictable.
In my own applications I regularly get throughput variations in the 10% range for the same input, with no apparent cause. It is for this reason that Java is not considered suitable for real-time applications either.
It might help us provide a better answer if you mentioned for what purpose you need to do something like that – and, perhaps, why you need to do in Java…