Artificial generation of cpu load in Java

2019-07-11 02:06发布

问题:

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

回答1:

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() + load
  while (current_system_time_ms() < time)
     // just consume some time for 60 ms 
  end

  SLEEP(100 - load);  // sleep for 40 ms
end 

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



回答2:

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.


回答3:

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:

// Creation
FakeLoad fakeload = FakeLoads.create()
    .lasting(30, TimeUnit.SECONDS)
    .withCpu(60);

// Execution
FakeLoadExecutor executor = 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 :)