Grzegorz Górkiewicz
Grzegorz Górkiewicz

Reputation: 4596

Basic (arithmetic) operations and their dependence on JVM and CPU

In Java I want to measure time for

  1. 1000 integer comparisons ("<" operator),
  2. 1000 integer additions (a+b each case for different a and b),
  3. another simple operations.

I know I can do it in the following way:

Random rand = new Random();
long elapsedTime = 0;
for (int i = 0; i < 1000; i++) {
    int a = Integer.MIN_VALUE + rand.nextInt(Integer.MAX_VALUE);
    int b = Integer.MIN_VALUE + rand.nextInt(Integer.MAX_VALUE);

    long start = System.currentTimeMillis();
    if (a < b) {}
    long stop = System.currentTimeMillis();
    elapsedTime += (start - stop);
}
System.out.println(elapsedTime);

I know that this question may seem somehow not clear.

How those values depend on my processor (i.e. relation between time for those operations and my processor) and JVM? Any suggestions?

I'm looking for understandable readings...

Upvotes: 1

Views: 253

Answers (1)

Peter Lawrey
Peter Lawrey

Reputation: 533750

How those values depend on my processor (i.e. relation between time for those operations and my processor) and JVM? Any suggestions?

It is not dependant on your processor, at least not directly.

Normally, when you run code enough, it will compile it to native code. When it does this, it removes code which doesn't do anything, so what you will be doing here is measuring the time it takes to perform a System.currentMillis(), which is typically about 0.00003 ms. This means you will get 0 99.997% of the time and see a 1 very rarely.

I say normally, but in this case your code won't be compiled to native code, as the default threshold is 10,000 iterations. I.e. you would be testing how long it takes the interpretor to execute the byte code. This is much slower, but would still be a fraction of a milli-second. i.e. you have higher chance seeing a 1 but still unlikely.

If you want to learn more about low level benchmarking in Java, I suggest you read JMH and the Author's blog http://shipilev.net/

If you want to see what machine code is generated from Java code I suggest you try JITWatch

Upvotes: 2

Related Questions