Is there a way to count the number of instructions in java

I want to know how many commands that my Java code consumes to execute. I am looking for an api that starts counting commands, and the final total number of commands should be returned at the end

For instance:

public static void main() { int a=0; int b=0; int c=0; startCountinst(); if(a==b) { c++; } int n = stopCountinst(); } 

At the end, n should represent the total number of commands executed after startCountinst() called. Is instruction counting possible in java?

+5
source share
4 answers

On Linux, you can run perf cpu-cycles . This will count the number of processor cycles the program uses. If you use perf list , you can see all other parameters for monitoring the application.

+2
source

I like the question. May be useful for measuring performance. But not every instruction takes equal time. Therefore, you better look at profiling your code.

JProfiler is quite popular:

https://www.ej-technologies.com/products/jprofiler/overview.html

And there are several free alternatives available. Just google for the java profiler and take a look. There is a lot of information.

+1
source

If you are interested in the number of JVM instructions, you can manually count them. A source:

 public static void main() { int a = 0; int b = 0; int c = 0; if (a == b) { c++; } } 

You can look at the bytecode by calling javap -c YouClassName :

 public static void main(); Code: 0: iconst_0 1: istore_0 2: iconst_0 3: istore_1 4: iconst_0 5: istore_2 6: iload_0 7: iload_1 8: if_icmpne 14 11: iinc 2, 1 14: return 

The if statement that interests you is up to 4 JVM instructions.

+1
source

When compiling a native C or C++ program, it will consist of a set of build commands (machines). Therefore, it makes sense to discuss the number of commands that will be executed when C / C++ code is run. However, when compiling the Java class, you create a .class file consisting of platform-independent byte code. The closest thing to the number of Java instructions will be the number of bytecode instructions.

R. Garbage has an Eclipse plugin for visualizing bytecode . You can determine the number of bytecode instructions by checking, and then find out how many complete instructions have been executed.

0
source

Source: https://habr.com/ru/post/1216662/


All Articles