Is there a simple way to generate a constan开发者_Python百科t CPU load in Java? Like generate CPU load at 60%.
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 :)
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 ... :)
I think that's not even possible, because:
- the way the JVM interprets code (provided it interprets code at all) is implementation-dependent
- 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.
精彩评论