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?
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With