Skip to content

Instantly share code, notes, and snippets.

@SriramKeerthi
Last active September 27, 2022 09:25
Show Gist options
  • Save SriramKeerthi/0f1513a62b3b09fecaeb to your computer and use it in GitHub Desktop.
Save SriramKeerthi/0f1513a62b3b09fecaeb to your computer and use it in GitHub Desktop.
Simple CPU Load Generator in Java
package com.caffinc.grex.core;
/**
* SPDX-License-Identifier: MIT
*
* Generates Load on the CPU by keeping it busy for the given load percentage
* @author Sriram
*/
public class Load {
/**
* Starts the Load Generation
* @param args Command line arguments, ignored
*/
public static void main(String[] args) {
int numCore = 2;
int numThreadsPerCore = 2;
double load = 0.8;
final long duration = 100000;
for (int thread = 0; thread < numCore * numThreadsPerCore; thread++) {
new BusyThread("Thread" + thread, load, duration).start();
}
}
/**
* Thread that actually generates the given load
* @author Sriram
*/
private static class BusyThread extends Thread {
private double load;
private long duration;
/**
* Constructor which creates the thread
* @param name Name of this thread
* @param load Load % that this thread should generate
* @param duration Duration that this thread should generate the load for
*/
public BusyThread(String name, double load, long duration) {
super(name);
this.load = load;
this.duration = duration;
}
/**
* Generates the load when run
*/
@Override
public void run() {
long startTime = System.currentTimeMillis();
try {
// Loop for the given duration
while (System.currentTimeMillis() - startTime < duration) {
// Every 100ms, sleep for the percentage of unladen time
if (System.currentTimeMillis() % 100 == 0) {
Thread.sleep((long) Math.floor((1 - load) * 100));
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@pradykaushik
Copy link

@SriramKeerthi and @pradykaushik - I'd like to fork your work for demoing autoscaling in the cloud. Would you be open to adding licenses to your code that would make that legal? For a gist, this should be enough: (explanation)

//SPDX-License-Identifier: MIT

I have added the license to my repository. If something does not work as intended please let us know by opening up an issue.

@SriramKeerthi
Copy link
Author

Added it, hope you get to build something cool with it.

@SriramKeerthi
Copy link
Author

I forked this gist and created a wrapper. Please check it out here on this.

That looks like a lot of good work done on this. I can't remember but I think I created a runnable jar version with a lot of configurations and a dashboard for this as well, but you seem to have put in a lot of work as well. Hope it's everything you want it to be.

@abhinavm24
Copy link

This is awesome! Thank you

@fredericdasilva
Copy link

Thanks! Very helpfull

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment