general concept-java code and cycle clocks

2019-07-15 21:58发布

问题:

I am just curious how can we know how many cycle clocks CPU needs by looking through certain java code.

ex:

public class Factorial
{
    public static void main(String[] args)
    {   final int NUM_FACTS = 100;
        for(int i = 0; i < NUM_FACTS; i++)
            System.out.println( i + "! is " + factorial(i));
    }

    public static int factorial(int n)
    {   int result = 1;
        for(int i = 2; i <= n; i++)
            result *= i;
        return result;
    }
}

回答1:

I am just curious how can we know how many cycle clocks CPU needs by looking through certain java code.

If you are talking about real hardware clock cycles, the answer is "You can't know"1.

The reason that it is so hard is that a program goes through a number of complicated (and largely opaque) transformations before and during execution:

  • The source code is compiled to bytecodes ahead of time. This depends on the bytecode compiler used.
  • The bytecodes are JIT compiled to native code, at some time during the execution. This depends on the JIT compiler in the execution platform AND on the execution behavior of the application.
  • The number of clock cycles taken to execute a given instruction sequence depends on native code, the CPU model including such things as memory cache sizes and ... the application's memory access patterns.
  • On top of that, the JVM has various sources of "under the hood" non-determinism, and various launch-time tuning parameters that influence the behavior ... and cycle counts.

But fortunately, there are practical ways to examine software performance that don't depend on measuring hardware clock cycles. You can:

  • measure or estimate native instructions executed,
  • measure or estimate bytecodes executed,
  • estimate Java-level operations or statements executed, or
  • run the code and measure the time taken.

The last two are generally the most practical.

1 - ... except by running the application / JVM on an accurate hardware-level simulator for your exact hardware configuration and getting the simulator to count the clock cycles. And to be honest, I don't know if simulators that operate to that level actually exist. If they do, they are most likely proprietary to Intel, AMD and so on.



回答2:

I don't think you'd be able to know the clock cycles.

But you could measure the CPU time it took to run the code.

You'd need to use the java.lang.management API.

Take a look here:

http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/management/ThreadMXBean.html