Skip to content Skip to sidebar Skip to footer

Artificial Generation Of Cpu Load In Java

Is there a simple way to generate a constant CPU load in Java? Like generate CPU load at 60%.

Solution 1:

Kind of late to the party, but just wanted to share that I created a small open-source client library called FakeLoad which can be used to generate different kinds of system load like CPU, memory, and disk I/O on the fly.

For instance, generating a CPU load of 60% for 30 seconds with FakeLoad can be done like this:

// CreationFakeLoadfakeload= FakeLoads.create()
    .lasting(30, TimeUnit.SECONDS)
    .withCpu(60);

// ExecutionFakeLoadExecutorexecutor= FakeLoadExecutors.newDefaultExecutor(); 
executor.execute(fakeload);

It doesn't provide perfect precision, but it is able to generate quite constant and accurate loads. It is available on Maven Central, so feel free to give it a try :)

Solution 2:

Have not tested this, but it might roughly work, to make your application work and sleep in the correct ratio. Something like (pseudocode):

load = 60;  
do forever
  time = current_system_time_ms() + loadwhile (current_system_time_ms() < time)
     // just consume some timefor60 ms 
  end

  SLEEP(100 - load);  // sleep for40 ms
end

Ok, you asked for a simple way, but ... :)

Solution 3:

I think that's not even possible, because:

  1. the way the JVM interprets code (provided it interprets code at all) is implementation-dependent
  2. the compiler, and the JVM, may optimize code (in an implementation-dependent manner, of course) so that you may run different bytecodes than the ones in a given .class file.

Post a Comment for "Artificial Generation Of Cpu Load In Java"