[ACCEPTED]-generate CPU load in Java-cpu

Accepted answer
Score: 23

You could try something simple like

private static void spin(int milliseconds) {
    long sleepTime = milliseconds*1000000L; // convert to nanoseconds
    long startTime = System.nanoTime();
    while ((System.nanoTime() - startTime) < sleepTime) {}
}

Test:

public static void main(String[] args) {
    final int NUM_TESTS = 1000;
    long start = System.nanoTime();
    for (int i = 0; i < NUM_TESTS; i++) {
        spin(500);
    }
    System.out.println("Took " + (System.nanoTime()-start)/1000000 +
        "ms (expected " + (NUM_TESTS*500) + ")");
}

My 3 output:

$ java SpinTest
Took 500023ms (expected 500000)

So the loop didn't get optimized 2 away (and yeah, I spiked my CPU to 100% for 1 eight minutes just to test this :)).

Score: 6

Encrypt a string (in a loop) by calling 6 Cipher.update(). Encryption algorithms 5 are by definition very difficult to optimize. The 4 only problem is that there is some non-trivial 3 setup you need to perform. I'm marking 2 this answer as community wiki, so that somebody 1 who's written it recently can fill it in.

Score: 4

Create a very large collection of random 3 objects and then alternate calls to Collections.shuffle() and 2 Collections.sort().

I used Jakarta Commons Lang to generate 1 random strings for the purposes of shuffling/sorting.

Score: 0

Create a matrix and do a couple of matrix 2 manipulations.

You can tune that pretty easily 1 by varying the size of the matrix.

Score: 0

Yet another stuff you can use, maybe :

        long start  = System.currentTimeMillis();
        long count = 0l;
        for(long x=0;x<Integer.MAX_VALUE ;x++){
            count+=1;
        }
        long end = System.currentTimeMillis();
        System.out.println(end-start +" ms");

0

More Related questions