CPU execution time in Java

前端 未结 5 1942
我寻月下人不归
我寻月下人不归 2020-12-03 03:44

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();
           


        
5条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-03 04:19

    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

    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.

提交回复
热议问题