Search code examples
javatimeexecution

CPU execution time in Java


I want to calculate how much CPU time my function takes to execute in Java. Currently I am doing as below.

   long startTime = System.currentTimeMillis();
    myfunction();
    long endTime = System.currentTimeMillis();
    long searchTime = endTime - startTime;

But I found out that for the same I/P I get different time depending on system load.

So, how to get exact CPU time my function took to execute.


Solution

  • As the JVM warms up the amount of time taken will vary. The second time you run this will always be faster than the first. (The first time it has to load classes and call static blocks) After you have run the method 10,000 times it will be faster again (The default threshold at which it compiles code to native machine code)

    To get a reproducable average timing for a micro-benchmark, I suggest you ignore the first 10,000 iterations and run it for 2-10 seconds after that.

    e.g.

    long start = 0;
    int runs = 10000; // enough to run for 2-10 seconds.
    for(int i=-10000;i<runs;i++) {
        if(i == 0) start = System.nanoTime();
        // do test
    }
    long time = System.nanoTime() - start;
    System.out.printf("Each XXXXX took an average of %,d ns%n", time/runs);
    

    Very important: Only do one of these loops per method. This is because it optimises the whole method based on how it is used. If you have one busy loop like this the later loops will appear slower because they have not run and will be optimised poorly.