Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 640
user3201343 Avatar asked Apr 02 '15 05:04

user3201343


3 Answers

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.

like image 73
Peter Lawrey Avatar answered Oct 20 '22 07:10

Peter Lawrey


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.

like image 21
Stefaan Neyts Avatar answered Oct 20 '22 07:10

Stefaan Neyts


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.

like image 2
fredoverflow Avatar answered Oct 20 '22 07:10

fredoverflow