generate CPU load in Java

后端 未结 5 1414
悲哀的现实
悲哀的现实 2020-12-31 07:18

I am conducting some throughput testing. My application has to

  1. read from JMS
  2. do some processing
  3. write to JMS

My goal here is t

相关标签:
5条回答
  • 2020-12-31 07:46

    Create a matrix and do a couple of matrix manipulations.

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

    0 讨论(0)
  • 2020-12-31 07:53

    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 讨论(0)
  • 2020-12-31 07:57

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

    0 讨论(0)
  • 2020-12-31 08:00

    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 output:

    $ java SpinTest
    Took 500023ms (expected 500000)
    

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

    0 讨论(0)
  • 2020-12-31 08:02

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

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

    0 讨论(0)
提交回复
热议问题