Reputation: 157
I want to know how many instructions my java code consumes to execute. I am looking for an api which starts the instruction count and the final total number of instructions should be returned at the end
For example:
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 instructions executed after calling startCountinst()
. Is it possible in java to count the instructions?
Upvotes: 7
Views: 5332
Reputation: 263350
If you're interested in the number of JVM instructions, you can count them by hand. 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 invoking 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 you were interested in compiles down to 4 JVM instructions.
Upvotes: 2
Reputation: 533870
On Linux you can run perf cpu-cycles This will count the number of CPU cycles a program uses. If you use perf list
you can see all the other options for monitoring an application.
Upvotes: 3
Reputation: 522712
A native C
or C++
program, when compiled, will consist of a set of assembly (machine) instructions. So it makes sense to discuss the number of instructions which will execute when running a C
/C++
code. However, when you compile a Java class, you generate a .class
file consisting of platform-independent bytecode. The closest thing to number of instructions of Java would be the number of bytecode instructions.
Dr. Garbage has an Eclipse plugin for visualizing bytecode. You could determine the number of bytecode instructions by inspection, and then figure out how many total instructions have been executed.
Upvotes: 0
Reputation: 2067
I like the question. Could be useful to measure performance. But not every instruction takes equal time. So you better look at profiling your code.
JProfiler is rather popular:
https://www.ej-technologies.com/products/jprofiler/overview.html
And there are several free alternatives available. Just Google for java profiler and have a look. Plenty of info available.
Upvotes: 2